问题
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/>";
}
}
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?
回答1:
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);
回答2:
Database initialization is triggered lazily by Entity Framework. It will only occur when EF tries to connect to the database. You can manually trigger database initialization using the following.
using (var db = new Models.TnHContext())
{
db.Database.Initialize(force: false);
}
Setting the force parameter to false tells EF not to run initialization if it has already been triggered.
来源:https://stackoverflow.com/questions/17303710/code-first-database-only-created-after-execute-certain-code