如何防止 DbContext 更改数据库? [英] How to prevent DbContext from altering the database?

查看:32
本文介绍了如何防止 DbContext 更改数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习实体框架(目前使用 EF6 测试版)并且我在现有数据库上使用代码优先模式.实体和 DbContext 类是使用 T4 模板自动创建的.

I'm learning Entity Framework (currently using EF6 beta) and I'm using the code first pattern on an existing database. The entities and DbContext class are created automatically using a T4 template.

我想阻止 DbContext 在运行时创建/更改数据库中的任何内容.

I would like to prevent the DbContext from creating / altering anything into the database at runtime.

我该怎么做?

推荐答案

当您执行 enable-migrations 命令时,您将看到文件夹 /Migrations,在该文件夹下可以找到名为 Configuration.cs 的文件.在该文件的构造函数中,默认情况下,有一个属性设置为 value:

When you do enable-migrations command, you will be presented with folder /Migrations under which you can find file named Configuration.cs. Within constructor of that file, by the default, there is a property set to value:

 AutomaticMigrationsEnabled = false;

这将确保您的数据库不会自动迁移,而是通过手动调用每个迁移.

Which will ensure that your database won't be migrated automatically, but rather by invoking each migration manually.

但是,如果您的数据库比域模型大,即您只是在现有数据库的一部分上进行操作,那么在您的应用程序中的某处启动(如果它是 ASP.NET 应用程序,Application_Startstrong> 事件处理程序),需要添加如下代码:

However, if your database is larger than your domain models, i.e. you're just operating on the portion of already existing database, then somewhere in your application start (if it is ASP.NET app, Application_Start event handler), you need to add the following code:

Database.SetInitializer<YourDbContext>(null);

否则,Entity Framework 会抱怨域模型中的数据库定义与数据库的实际当前状态不匹配.

Otherwise, Entity Framework will complain that there is a mismatch between database definition in your domain model and actual current state of the database.

如果您想确保 YourDbContext 没有尝试更改数据库,请执行以下操作:

If you want to be sure that YourDbContext is not attempting to change database, do this:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    throw new YourCustomException("Code first changes are not allowed."); 
}

再次

我正在尝试了解您要完成的场景.如果您有现有的数据库,并且您想更新它但只能手动更新,则方法如下:

I'm trying to understand what scenario are you trying to accomplish. If you have existing database, and you want to update it but only manually, this is the approach:

  1. 使用 DbContext 生成器模板生成 DbContext 和实体从现有数据库.
  2. 运行启用迁移
  3. 做 add-migration Initial
  4. 如果一切都完成了,第 3 步应该会生成空迁移适当地.你可以删除它.
  5. 现在每当你做一些改变时,你需要做 add-migration更换名字.这不会去数据库,除非你这样做更新数据库.

这篇关于如何防止 DbContext 更改数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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