問題描述
我從表單 POST 接收到 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.
推薦答案
在 LinqToSQL 設計器中,將所有更新檢查設置為從不,當你附加時,像這樣調用它:
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);
或者,您也可以從數據庫中獲取實體并使用來自 POSTed 實體的數據對其進行更改,然后將其作為更改提交.
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.
這篇關于LINQ 中的實體附件問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!