如何从代码优先创建数据库?相当于LINQ2SQL context.GetTable [英] How to create a database from code-first? Equivalent to LINQ2SQL context.GetTable
问题描述
背景:
我有LINQ-to-SQL代码,所有对象都是使用属性/数据注释的POCO(普通旧CLR对象)。我没有映射文件。我正在迁移到Entity Framework并希望使用"Code-First"从我的域
模型(代码中)生成我的数据库。我没有.edmx,没有.ssdl等类型元文件。
I have LINQ-to-SQL code and all my objects are POCO (plain old CLR objects) that use attributes/data annotations. I have no mapping files. I am migrating to Entity Framework and would like to use "Code-First" to also generate my database from my domain model (in code). I have no .edmx, no .ssdl, etc. type meta files.
我正在寻找类似这样的LINQ-to-SQL:
I'm looking for the LINQ-to-SQL equivalent of something like this:
DataContext context = new DataContext(connString);
context.GetTable<MyEntity>();
context.CreateDatabase();
有人在另一个论坛上问过类似的问题并建议使用ObjectContext而不是DbContext,所以我的方法现在看起来像这样:
Someone asked a similar question in another forum and recommended using ObjectContext instead of DbContext, so my method now looks like this:
ObjectContext oContext = new ObjectContext(connectionString);
if (oContext.DatabaseExists())
oContext.DeleteDatabase();
oContext.CreateQuery<MyEntity>(typeof(MyEntity).Name);
oContext.CreateDatabase();
推荐答案
iam_ray,
Code First能够为您创建数据库。
您可以使用数据库初始化程序自动执行此操作,也可以使用DbContext上Database属性中的方法手动执行此操作。
我建议你仔细阅读这篇演练: http://blogs.msdn.com/b /adonet/archive/2010/12/14/ef-feature-ctp5-code-first-walkthrough.aspx ,
特别是关于数据库初始化器的部分。 另请查看DbDatabase上的方法,这些方法可以从DbContext的Database属性访问。
(请注意,在这种情况下使用ObjectContext不太可能帮助您。)
Code First is able to create a database for you. You can use database initializers to do this automatically or you can do it manually using the methods from the Database property on DbContext. I would suggest having a read through this walk-through: http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-code-first-walkthrough.aspx, especially the section on database initializers. Also take a look at the methods on DbDatabase, which is accessed from the Database property of your DbContext. (Note that using ObjectContext is unlikely to help you in this case.)
希望这会有所帮助。
谢谢,
< span style ="font-size:small"> Arthur
这篇关于如何从代码优先创建数据库?相当于LINQ2SQL context.GetTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!