EF CodeFirst:DropCreateDatabaseIfModelChanges 不起作用
我在 Global.asax: 中使用以下代码:
DbDatabase.SetInitializer<MyDBContext>
(new DropCreateDatabaseIfModelChanges<MyDBContext>());
但它似乎不起作用。
尽管我的模型已更改,并且我正在尝试使用新添加的表之一,但它只是说找不到该表。
Invalid object name 'dbo.TableName'.
但是,如果我运行它,它似乎可以工作,并且正在创建表:
DbDatabase.SetInitializer<MyDBContext>(new DropCreateDatabaseAlways<MyDBContext>());
它确实更新了我的数据库。
我做错了什么?
I use the following code in my Global.asax:
DbDatabase.SetInitializer<MyDBContext>
(new DropCreateDatabaseIfModelChanges<MyDBContext>());
but it doesn't seem to work.
Although my Model has changed and I'm trying to use one of the newly added table's it just says the table could not be found.
Invalid object name 'dbo.TableName'.
If I run this however, it seems to work, and the table is being created:
DbDatabase.SetInitializer<MyDBContext>(new DropCreateDatabaseAlways<MyDBContext>());
It does update my database.
What is it I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无论如何,我在使用 DropCreate 策略时都遇到了很多麻烦,因为在我关闭浏览器后 Cassini 仍在运行。 (我在 IIS Express 上也遇到了同样的问题。)由于本地 Web 服务器仍在运行,
Application_Start
没有再次触发,因此我放在那里的初始化从未执行。我通过启用“编辑并继续”解决了这个问题:
项目属性 > 网络> 调试器 > 启用编辑并继续
这会强制本地 Web 服务器在浏览器关闭时关闭。
For what it's worth, I ran into a lot of trouble with both of the DropCreate strategies because Cassini was still running after I closed the browser. (I had the same problem with IIS Express.) Because the local web server was still running,
Application_Start
didn't fire again, so the initialization I put there never got executed.I resolved it by enabling Edit and Continue:
Project properties > Web > Debuggers > Enable Edit and Continue
This forces the local web server to close when the browser closes.
原来是master数据库的用户权限。奇怪的是,使用 DropCreateDatabaseAlways 不需要主数据库的权限,而 IfModelChanges 则需要。
It turned out to be user permissions on the master database. Weird that using DropCreateDatabaseAlways is doesn't need permissions on the master database, where IfModelChanges does.
我遇到了同样的问题:
就我而言,当我添加上面的代码行时,数据库已经存在。我删除了数据库并再次运行我的程序,它开始按预期工作。只有其他冲突可能是原因是我一直在数据库上使用“启用迁移”。
华泰
I had the same issue with:
In my case, the database had already existed when i added the above line of code. I dropped the db and ran my program again and it started working as expected. Only other conflict might've been the cause is I had been playing with 'Enable-Migrations' on the database.
HTH
如果您删除了 IncludeMetadataConvention,则预期会出现此行为:
modelBuilder.Conventions.Remove();
This behaviour is expected in case you removed IncludeMetadataConvention:
modelBuilder.Conventions.Remove<System.Data.Entity.Database.IncludeMetadataConvention>();