//自动根据Linq实体创建库和表
public static class CreatDataTable
{
private static string dbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AdvertisementDatabaseConnectionString"].ConnectionString;
public static void CheckDataTableIsExists()
{
DBDataContext db = new DBDataContext(dbConnectionString);
if (db.DatabaseExists() == false)
{
db.CreateDatabase();
}
CreateTables();
}
/// <summary>
/// 创建单个表
/// </summary>
/// <param name="linqTableClass"></param>
public static void CreateTable(Type linqTableClass)
{
using (var tempDc = new DBDataContext(dbConnectionString))
{
var metaTable = tempDc.Mapping.GetTable(linqTableClass);
//反射的方法创建对象
var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
var type = typeof(DataContext).Assembly.GetType(typeName);
//反射调用私有的GetCreateTableCommand 方法。
var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
var sqlAsString = sql.ToString();
tempDc.ExecuteCommand(sqlAsString);
}
}
/// <summary>
/// 创建所有的表,如果已存在则不会再创建
/// </summary>
public static void CreateTables( )
{
using (var tempDc = new DBDataContext(dbConnectionString))
{
var tables = tempDc.Mapping.GetTables();
foreach (var metaTable in tables)
{
try
{
//var metaTable = tempDc.Mapping.GetTable(linqTableClass);
//反射的方法创建对象
var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
var type = typeof(DataContext).Assembly.GetType(typeName);
//反射调用私有的GetCreateTableCommand 方法。
var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
var sqlAsString = sql.ToString();
tempDc.ExecuteCommand(sqlAsString);
}
catch (SqlException sqlex)
{
if (sqlex.Number == 2714)
{
//这个表已存在,不需要再创建
}
else
{
throw;
}
}
}
}
}
}
自动根据Linq实体创建库和表
当然应该放在应用程序启动的时候或者iis启动的时候只执行一次。。