用过Linq To SQL的朋友都清楚,DataContext 有 CreateDatabase() 这个方法,但是却没有CreateTable(),有些情况下,还是需要CreateTable()的,比如说在虚拟主机上,一般都是没有建立数据库的权限。代码比较简单,看一下就明白了。
Code
namespace ALinq.Mapping
{
class CreateTableDemo
{
[Table(Name = "User")]
class User
{
[Column]
public int ID;
[Column]
public string Name;
}
static void Main()
{
var constr = @"Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=DemoDataContext;Integrated Security=True";
var context = new DataContext(constr) { Log = Console.Out };
var metaTable = context.Mapping.GetTable(typeof(User));
Debug.Assert(metaTable != null);
var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
var type = typeof(DataContext).Assembly.GetType(typeName);
var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
Console.WriteLine(sql);
//Excute SQL Command
}
}
}
namespace ALinq.Mapping
{
class CreateTableDemo
{
[Table(Name = "User")]
class User
{
[Column]
public int ID;
[Column]
public string Name;
}
static void Main()
{
var constr = @"Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=DemoDataContext;Integrated Security=True";
var context = new DataContext(constr) { Log = Console.Out };
var metaTable = context.Mapping.GetTable(typeof(User));
Debug.Assert(metaTable != null);
var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
var type = typeof(DataContext).Assembly.GetType(typeName);
var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
Console.WriteLine(sql);
//Excute SQL Command
}
}
}