简体   繁体   中英

Entity attachment issues in LINQ

I am trying to attach a LINQ entity to the data context after I receive it from a form POST. However, all I get is the following exception:

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.

I have also tried attaching the original row, like so:

dataContext.People.Attach(person, originalPerson);

In this case, I get the following exception:

Object reference not set to an instance of an object.

Here's the code in my controller:

[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");
}

Any ideas on what I'm doing wrong here? I can post the entity code if needed.

Try following:

dataContext.People.Attach(person);
dataContext.Refresh(RefreshMode.KeepCurrentValues, person);
dataContext.SubmitChanges();

In the LinqToSQL designer set all of the Update Checks to Never and when you attach call it like so:

 context.entity.Attach(entity, true);

Alternatively, you could also grab the entity from the db and change it using the data from the POSTed entity, then submit that as a change.

我通过在.Dbml文件和context.entity.Attach(entity, true);中将UpdateCheck=Never设置为我的属性来解决context.entity.Attach(entity, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM