0

I have one piece of code that gets run on Application_Start for seeding demo data into my database, but I'm getting an exception saying:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

While trying to enumerate one of my entities DB.ENTITY.SELECT(x => x.Id == value);

I've checked my code and I'm not disposing my context before my operation, Below is an outline of my current implementation:

protected void Application_Start()
{
   SeedDemoData();
}

public static void SeedDemoData()
{
   using(var context = new DBContext())
   {
       // my code is run here.
   }
}

So I was wondering if Application_Start is timing out and forcing my db context to close its connection before it completes.

Note: I know the code because I'm using it on a different place and it is unit tested and over there it works without any issues.

Any ideas of what could be the issue here? or what I'm missing?

4

1 回答 1

1

在调查了这个问题几个小时后,我发现它是由数据上下文在不同的线程上有待处理的更改引起的。我们当前的数据库升级/迁移实现在 App_Start 方法的并行线程上运行,因此我注意到我尝试枚举的实体同时被更改,即使它们在不同的数据上下文中运行 EF 注意到访问实体时出现问题并返回不正确的错误消息,说明数据上下文已被释放,而实际异常是实体状态已修改但未保存。

我的问题的实际解决方案是将所有种子数据功能移动到数据库升级/迁移脚本中,以便实体一次只在一个地方修改。

于 2013-03-11T20:48:51.083 回答