linq .dbml转化成sql脚本
public String ConvertDBMLToSqlScript(System.Data.Linq.DataContext DBContext)
{
String DBContextNamespace = DBContext.GetType().Namespace;
StringBuilder sqlScriptCollection = new StringBuilder();
String[] DotNeedArr = new String[]
{
"Connection","Transaction","CommandTimeout",
"Log", "ObjectTrackingEnabled","DeferredLoadingEnabled",
"Mapping","LoadOptions","ChangeConflicts"
};
foreach (PropertyInfo p in DBContext.GetType().GetProperties())
{
if (DotNeedArr.Contains(p.Name)) continue;
string sqlScript = "create table "+p.Name+" (";
Type type = Type.GetType(DBContextNamespace+"." + p.Name);
foreach (System.Reflection.PropertyInfo mInfo in type.GetProperties())
{
foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
if (attr.GetType() == typeof(ColumnAttribute))
{
ColumnAttribute ColumnAttr = attr as ColumnAttribute;
sqlScript += "[" + mInfo.Name + "] ";
if (ColumnAttr.DbType.Contains("NULL"))
sqlScript+=ColumnAttr.DbType;
else
sqlScript+=ColumnAttr.DbType+" null ";
if (ColumnAttr.IsPrimaryKey)
{
sqlScript += " primary key ";
}
sqlScript += ",";
}
}
}
sqlScript = sqlScript.Substring(0, sqlScript.Length - 1);
sqlScript += ")";
sqlScriptCollection.AppendLine(sqlScript);
}
return sqlScriptCollection.ToString();
}
DataClasses1DataContext DBContext = new DataClasses1DataContext();
String resultSql = ConvertDBMLToSqlScript(DBContext);