如何停止EF检测我的数据库/模型的更改

时间:2013-03-11 06:17:34

标签: entity-framework

我的代码中有以下内容:

 DbContext = new DataContext();
 DbContext.Configuration.AutoDetectChangesEnabled = false;

然后在我的控制器方法中:

// GET /api/Applications
public IEnumerable<Application> Get()
{
    return _uow.Applications.GetAll().OrderBy(p => p.Name);
}

但是我仍然收到以下消息:

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The model backing the 'DataContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
  Source=EntityFramework
  StackTrace:

有人可以解释为什么会这样。我认为创建上下文后的行会停止此检查。

3 个答案:

答案 0 :(得分:9)

您可以放置​​(这是一种静态方法)

Database.SetInitializer<DataContext>(null);

在您第一次使用DataContext之前。但请注意,这将关闭它。完成。如果您的数据库与型号不兼容,您的查询等将失败。

答案 1 :(得分:0)

这是因为您的实体模式与数据库架构有所不同。错误在于您需要根据代码中的新模型更新数据库模式。

AutoDetectChangesEnabled not something related to this error。因为它是关于跟踪数据的更改,而您获得的错误与数据库架构的更改有关。

错误消息建议您根据数据模型中的更改使用code first migrations更新数据库架构。

答案 2 :(得分:0)

您有2个选择:

1。通过将以下行放在派生的DbContext的构造函数中,将您的上下文的初始化程序设置为null

Database.SetInitializer<MyContext>(null);

2。通过在Web.config节点内添加Key,在appSettings文件中禁用数据库初始化程序:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>    
    <add key="DatabaseInitializerForType YourNamespace.YourDbContext, YourAssemblyName"
            value="Disabled" />
    </appSettings>
</configuration>

在应用程序中用相应的值替换YourNamespace.YourDbContextYourAssemblyName