Code first: Database only created after execute certain code?

不羁的心 提交于 2020-01-02 06:45:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!