当我运行以下代码时:
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();
上得到了Exception"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."
答案 0 :(得分:2)
我创建了一个名为applicationController的类,它派生自Controller。然后我让我的所有控制器类派生自此。 applicationController类有一个constrcutor,它可以在整个应用程序中使用我的存储库(或实例中的datacontext)的新实例:
public class ApplicationController : Controller
{
private VeriTabanDataContext _datacontext;
public ApplicationController() : this(new VeriTabanDataContext())
{
}
public ApplicationController(VeriTabanDataContext datacontext)
{
_datacontext = datacontext;
}
Public VeriTabanDataContext DataContext
{
get { return _datacontext; }
}
}
然后您可以在所有控制器中使用它
public class MyController : ApplicationController
{
public ActionResult Complete()
{
DataContext.Persons.InsertOnSubmit(_person);
DataContext.SubmitChanges();
return View(_person);
}
}
目前没有安装VS的电脑上没有测试此代码....
希望这可以解决问题-Mark
答案 1 :(得分:1)
你能做到以下几点:
var foundPerson = db.Person.FirstOrDefault( p => p.Id == _person.Id);
if(foundPerson == null)
{
db.InsertOnSubmit(_person);
}else{
Mapper.Map(_person,foundPerson);
}
db.SubmitChanges();
return View(_person);
我使用AutoMapper从一个实体映射到另一个实体。为此,请将AutoMapper的引用添加到您的项目中,并在启动代码中添加您需要配置映射的应用程序,以便上述工作所需:
Mapper.CreateMap<Person, Person>().ForMember(src => src.Id, opt => opt.Ignore());