首页 > 数据库技术 > 详细

linq .dbml转化成sql脚本

时间:2015-01-18 18:23:13      阅读:313      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!