码迷,mamicode.com
首页 > 数据库 > 详细

linq .dbml转化成sql脚本

时间:2015-01-18 18:24:25      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

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

linq .dbml转化成sql脚本

标签:

原文地址:http://www.cnblogs.com/webwang/p/4231999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!