我有一个 EF DataRepository 模式,它是我从头开始设计的,在通过使用它的 Web 应用程序使用 EF 时效果很好,但我的任务是为我的系统生成一个运行良好的 WCF API 版本仅检索数据时。
当我尝试创建新对象时(这些对象是在 Web 服务方法中创建的,而不是从请求中序列化的)我遇到了以下问题:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
现在我之前在开发系统时已经看到了这一点,但这是因为我为每次调用创建了一个新的上下文,我通过将我的上下文放入 HttpContext.Current.Items 来解决这个问题正如我所说,在 Web 应用程序中效果很好,但现在当我调用代码给我上下文时,HttpContext 为 Null(正如预期的那样),因此代码将再次为方法中的每个调用生成一个新的上下文。
为了解决这个问题,我让我的服务提供商能够在初始化服务提供商时发送上下文(作为参数)。 然后我在方法的开头声明上下文,这意味着此方法中的所有调用都使用相同的上下文。
但我仍然遇到同样的问题?
示例代码:
public MyObject DoSomething()
{
var dbContext = new myContext();
var foos = new FooHelper(dbContext).GetAllFoos();
var bah = new bah();
bah.Foo = foos.First();
bah.title = "youre a real object";
new bahHelper(dbContext).Create(bah);
}
最佳答案
尝试正确处理上下文并测试错误是否消失:
public MyObject DoSomething()
{
using (var dbContext = new myContext())
{
var foos = new FooHelper(dbContext).GetAllFoos();
var bah = new bah();
bah.Foo = foos.First();
bah.title = "youre a real object";
new bahHelper(dbContext).Create(bah);
}
}
关于c# - EF 4.2 DbContext IEntityChangeTracker 问题的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258791/