代码第一:数据库是否在执行某些代码后创建? [英] Code first: Database only created after execute certain code?
问题描述
我想先使用代码创建一个数据库。
我的数据库始终处于DropCreateDatabaseAlways模式。
I want to create a database using code first. And my database is always in "DropCreateDatabaseAlways" mode.
我注意到,如果我不尝试对数据库执行一些查询,例如
I notice that, if I don't try to execute some query against the database, such as
using (var db = new Models.TnHContext())
{
var query = from u in db.Users
select u;
foreach (var u in query)
{
txt += u.UserID + "<br/>";
}
}
不会创建数据库。除非我执行它,否则只能看到创建的数据库。想知道这是否是由于EntityFramework设计/默认行为?
the database won't be created. Unless I execute it, only I can see the database created. Wonder if this is due to EntityFramework design/default behavior?
推荐答案
数据库初始化程序在对上下文执行查询时被调用,检索 ObjectContext
从 DbContext
,或者调用 Database.Initialize
方法。
The database initializer is called when you execute a query against the context, retrieve the ObjectContext
from the DbContext
, or call the Database.Initialize
method.
因此,如果要立即创建数据库而不执行查询,则应该使用:
Therefore, if you want to create the database immediately without executing a query, you should use:
context.Database.Initialize(false);
这篇关于代码第一:数据库是否在执行某些代码后创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!