在ASP.NET MVC 2中,使用实体框架4时,出现“IEntityChangeTracker的多个实例无法引用实体对象”的错误。每个HttpContext只使用一个ObjectContext的C#实体框架
SO的搜索表明它可能是因为我有不同的实体框架ObjectContext的实例,它应该只是每个HttpContext的一个ObjectContext实例。
我有这样的代码(写入很久之前我加入),似乎做到这一点 - 每个HttpContext有一个ObjectContext。但我经常收到“IEntityChangeTracker”异常所以它可能不会如预期运行:
// in ObjectContextManager.cs
public const string ConnectionString = "name=MyAppEntities";
public const string ContainerName = "MyAppEntities";
public static ObjectContext GetObjectContext()
{
ObjectContext objectContext = GetCurrentObjectContext();
if (objectContext == null) // create and store the object context
{
objectContext = new ObjectContext(ConnectionString, ContainerName);
objectContext.ContextOptions.LazyLoadingEnabled = true;
StoreCurrentObjectContext(objectContext);
}
return objectContext;
}
private static void StoreCurrentObjectContext(ObjectContext objectContext)
{
if (HttpContext.Current.Items.Contains("EF.ObjectContext"))
HttpContext.Current.Items["EF.ObjectContext"] = objectContext;
else
HttpContext.Current.Items.Add("EF.ObjectContext", objectContext);
}
private static ObjectContext GetCurrentObjectContext()
{
ObjectContext objectContext = null;
if (HttpContext.Current.Items.Contains("EF.ObjectContext")
objectContext = (ObjectContext)HttpContext.Current.Items["EF.ObjectContext"];
return objectContext;
}
我已经研究这个代码,它看起来是正确的。它尽我所能地告诉为每个HttpContext返回一个ObjectContext实例。代码是否错误?
如果代码没有错,为什么我会得到“一个实体对象不能被多个IEntityChangeTracker实例引用”异常?
编辑:要显示的ObjectContext是如何布置:
// in HttpRequestModule.cs
private void Application_EndRequest(object source, EventArgs e)
{
ServiceLocator.Current.GetInstance<IRepositoryContext>().Terminate();
}
// in RepositoryContext.cs
public void Terminate()
{
ObjectContextManager.RemoveCurrentObjectContext();
}
// in ObjectContextManager.cs
public static void RemoveCurrentObjectContext()
{
ObjectContext objectContext = GetCurrentObjectContext();
if (objectContext != null)
{
HttpContext.Current.Items.Remove("EF.ObjectContext");
objectContext.Dispose();
}
}
你在EndRequest方法中处理上下文吗? – Akhil
已更新为显示处置方法 –