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);

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。