LINQ 中的实体附件问题

Entity attachment issues in LINQ(LINQ 中的实体附件问题)
本文介绍了LINQ 中的实体附件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我从表单 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 中的实体附件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)