实体框架4代码第一 - 防止DB丢弃/创建 [英] Entity Framework 4 Code First - Prevent DB Drop/Create

查看:101
本文介绍了实体框架4代码第一 - 防止DB丢弃/创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Code First范例编写了一个ASP.Net MVC 3应用程序,当我对模型进行更改时,Entity Framework会自动尝试通过DROP和CREATE语句重新创建底层的SQL Server数据库。问题是应用程序托管在第三方远程服务器上,限制了我可以拥有的数据库数量,似乎不允许我从此错误消息中收集编程方式执行CREATE DATABASE ...语句:


数据库'master'中拒绝CREATE DATABASE权限。


有没有办法阻止实体框架丢弃并尝试重新创建整个数据库,而是简单地删除表并重新创建它们?



在手动创建数据库并运行应用程序后,我也会看到以下错误,因为Entity Framework尝试修改数据库:


由于数据库不包含模型元数据,因此无法检查模型兼容性。确保将IncludeMetadataConvention添加到DbModelBuilder约定中。



解决方案

更新: / strong>通过google找到这个宝石,听起来就像你所需要的那样: http://nuget.org/Tags / IDatabaseInitializer



您可以使用其他数据库初始化程序。假设你的上下文被称为 SampleContext ,那么你的构造函数将如下所示:

  public SampleContext()
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists< SampleContext>());
}

请注意,以上是默认的初始化程序。您可能需要通过实现 IDatabaseInitializer 来创建自己的自定义初始化程序。这里有一些很好的信息: http: //sankarsan.wordpress.com/2010/10/14/entity-framework-ctp-4-0-database-initialization/


I've written an ASP.Net MVC 3 application using the Code First paradigm whereby when I make a change to the model the Entity Framework automatically attempts to re-create the underlying SQL Server Database via DROP and CREATE statements. The problem is the application is hosted on a 3rd party remote server which limits the number of databases I can have and does not seem to allow me to programmatically execute "CREATE DATABASE..." statements as I gather from this error message:

CREATE DATABASE permission denied in database 'master'.

Is there any way to stop the Entity Framework from dropping and attempting to re-create the whole database and instead make it simply drop the tables and re-create them?

After creating the database manually and running the application I also get the following error I guess as the Entity Framework tries to modify the database:

Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.

解决方案

UPDATE: Found this gem through google, it sounds like its exactly what you need: http://nuget.org/Tags/IDatabaseInitializer

You can use a different database initializer. Lets say your context is called SampleContext then your constructor would look like this:

    public SampleContext() 
    {
        System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<SampleContext>()); 
    }

Note that the above is the default initializer. You will probably need to create your own custom initializer by implementing IDatabaseInitializer. Theres some good info here: http://sankarsan.wordpress.com/2010/10/14/entity-framework-ctp-4-0-database-initialization/

这篇关于实体框架4代码第一 - 防止DB丢弃/创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆