当我运行以下代码时:
public ActionResult Complete()
{
try
{
VeriTabanDataContext db = new VeriTabanDataContext();
db.Persons.InsertOnSubmit(_person);
db.SubmitChanges();
return View(_person);
}
catch (Exception ex)
{
return RedirectToAction("Error", ex);
}
}
我在 SubmitChanges() 上遇到异常;
"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."
- 这里的“_person”对象取自 Session,是一个良好的信誉。注意:_person 是多步向导的结果,这是我将新的 Person 对象添加到数据库的地方。
- 我的 Person 表有 9 个关系,我不能按照一些极客的建议为每个人添加版本列
- 我已经对这个问题进行了大量调查并花了 2 天的时间,但仍然无法解决。其他人建议的一些变通办法不能解决我的问题,而其他人似乎只是肮脏的变通办法。考虑到 Person 类有很多关系,而且在表中添加一列也不行,各位专家对此问题有好的解决方案吗?
- 我还想指出,我尝试使用“db.Persons.Attach(_person)”并设置 db.DeferredLoadingEnabled = false;这次我没有收到任何异常,但数据未保存到数据库
最佳答案
我创建了一个名为 applicationController 的类,它派生自 Controller。然后我让我所有的 Controller 类都派生自它。 applicationController 类有一个构造器,它创建我的存储库(或您实例中的数据上下文)的新实例,该实例在整个应用程序中使用:
public class ApplicationController : Controller
{
private VeriTabanDataContext _datacontext;
public ApplicationController() : this(new VeriTabanDataContext())
{
}
public ApplicationController(VeriTabanDataContext datacontext)
{
_datacontext = datacontext;
}
Public VeriTabanDataContext DataContext
{
get { return _datacontext; }
}
}
然后你可以在你所有的 Controller 中使用它
public class MyController : ApplicationController
{
public ActionResult Complete()
{
DataContext.Persons.InsertOnSubmit(_person);
DataContext.SubmitChanges();
return View(_person);
}
}
目前我的电脑上没有安装 VS,所以没有测试这段代码....
希望这能解决问题 - 马克
关于asp.net-mvc - "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1733822/