我正在使用带有Web窗体的EF 5(ASP.NET 4.5),以及“每个请求一个DbContext实例”方法。
但是这种情况有点复杂:我有一个多步创建/编辑屏幕,我将当前实体存储在Session中,然后我操纵它,在最后一步,我将它提交到数据库。
创建一个新实例很好,但我不能为我的生活编辑一个现有实体...因为它是另一个请求,我的原始DbContext实例丢失了,当我将它附加到一个新实例时,我得到了 IEntityChangeTracker的多个实例错误无法引用实体对象。
我的代码太复杂了,无法在此发布,但我会尝试准确地总结一下:
我的DbContext:
public class AppContext : DbContext
{
// DbSet declarations...
public static AppContext Current {
get { var context = HttpContext.Current.Items["Contexts.AppContext"] as AppContext;
if (context == null)
{
context = new AppContext();
HttpContext.Current.Items["Contexts.AppContext"] = context;
}
return context;
}
}
}
页面代码的示例:
protected void Page_Load(object sender, EventArgs e)
{
int? id = null; // After this, I try to get it from the QueryString, parse it, etc.. Omitted for sake of brevity
// If I have an ID, it means I'm editing...
Session["Product"] = id.HasValue ? new Product() : AppContext.Current.Products.Find(id));
MethodToPopulateFields(); // Internally, it uses the Session variable
}
protected void Step1(){ // through n
// Manipulates the Session["Product"] based on page input...
}
protected void Save(){
var product = Session["Product"] as Product;
if(product.ID == 0)
product = AppContext.Current.Products.Add(product);
// throws an exception:
// AppContext.Current.Entry(product).State = EntityState.Modified;
// this too:
// AppContext.Products.Attach(product);
AppContext.Current.SaveChanges();
}
我知道我可以从数据库中获取旧实体,手动更新并保存,所有这些都在最后一步,但我真的不想这样做......
谢谢。
答案 0 :(得分:0)
尝试拨打
AppContext.Current.Entry(product).State = EntityState.Detached;
在第一种方法中。