LINQ中的实体附件问题

cha*_*log 16 c# asp.net-mvc linq-to-sql

我在从表单POST收到LINQ实体后尝试将它附加到数据上下文中.但是,我得到的只是以下异常:

An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
Run Code Online (Sandbox Code Playgroud)

我也试过附加原始行,如下所示:

dataContext.People.Attach(person, originalPerson);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我得到以下异常:

Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

这是我的控制器中的代码:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Person person) {
    var prevPerson = dataContext.People.Single(p => p.ID == id);
    dataContext.People.Attach(person, prevPerson);
    dataContext.SubmitChanges();
    return Redirect("~/People/Index");
}
Run Code Online (Sandbox Code Playgroud)

关于我在这里做错了什么的想法?如果需要,我可以发布实体代码.

Rom*_*n O 16

试试以下:

dataContext.People.Attach(person);
dataContext.Refresh(RefreshMode.KeepCurrentValues, person);
dataContext.SubmitChanges();
Run Code Online (Sandbox Code Playgroud)


Ben*_*tin 12

在LinqToSQL设计器中,将所有更新检查设置为从不,当您附加调用时,如下所示:

 context.entity.Attach(entity, true);
Run Code Online (Sandbox Code Playgroud)

或者,您也可以从数据库中获取实体并使用POSTed实体中的数据进行更改,然后将其作为更改提交.