sql - LINQ SQL 附加,更新检查设置为从不,但仍然存在并发冲突

标签 sql linq sql-update

在 dbml 设计器中,我将所有属性的更新检查设置为从不。但是我在执行 Attach 时仍然遇到异常:“已尝试附加或添加一个不是新的实体,可能是从另一个 DataContext 加载的。这不受支持。”这种方法似乎对这里的其他人有效,但一定有我遗漏的地方。

        using(TheDataContext dc = new TheDataContext())
        {
            test = dc.Members.FirstOrDefault(m => m.fltId == 1);
        }

        test.Name = "test2";

        using(TheDataContext dc = new TheDataContext())
        {
            dc.Members.Attach(test, true);
            dc.SubmitChanges();
        }

最佳答案

错误消息准确说明了问题所在:您正在尝试附加从另一个 DataContext 加载的对象,在您的例子中是从 DataContext 的另一个实例加载的。在更改值并提交更改之前,不要处置您的 DataContext(在它被处置的 using 语句的末尾)。这应该有效(全部在一个 using 语句中)。我刚刚看到您想再次将该对象附加到成员集合,但它已经在那里了。不需要这样做,这应该也能正常工作:

using(TheDataContext dc = new TheDataContext())
{
    var test = dc.Members.FirstOrDefault(m => m.fltId == 1);
    test.Name = "test2";
    dc.SubmitChanges();
}

只需更改值并提交更改即可。

最新更新:

(删除了所有之前的 3 个更新)

我以前的解决方案(从这篇文章中再次删除它),找到here很危险。我刚刚在 MSDN article 上读到这篇文章:

"Only call the Attach methods on new or deserialized entities. The only way for an entity to be detached from its original data context is for it to be serialized. If you try to attach an undetached entity to a new data context, and that entity still has deferred loaders from its previous data context, LINQ to SQL will thrown an exception. An entity with deferred loaders from two different data contexts could cause unwanted results when you perform insert, update, and delete operations on that entity. For more information about deferred loaders, see Deferred versus Immediate Loading (LINQ to SQL)."

改用这个:

// Get the object the first time by some id
using(TheDataContext dc = new TheDataContext())
{
    test = dc.Members.FirstOrDefault(m => m.fltId == 1);
}

// Somewhere else in the program
test.Name = "test2";

// Again somewhere else
using(TheDataContext dc = new TheDataContext())
{
    // Get the db row with the id of the 'test' object
    Member modifiedMember = new Member()
    {
        Id = test.Id,
        Name = test.Name,
        Field2 = test.Field2,
        Field3 = test.Field3,
        Field4 = test.Field4
    };

    dc.Members.Attach(modifiedMember, true);
    dc.SubmitChanges();
}

复制对象后,所有引用都被分离,所有事件处理程序(从数据库延迟加载)都没有连接到新对象。只是将值字段复制到新对象,现在可以将其附加到成员表中。此外,您不必使用此解决方案第二次查询数据库。

关于sql - LINQ SQL 附加,更新检查设置为从不,但仍然存在并发冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607372/

相关文章:

c# - LinQ 选择一个以列表作为参数的对象

c# - LINQ for CRM 如何在 where 子句中使用 C# 列表

c# - NHibernate 左连接与 linq

mysql - 如何使用触发器更新 MySQL 中的不同表?

MySQL 根据其他表中的值更新表列

sql - Oracle 中的条件更新语句

sql - 找出每学期和每门类(class)中得分最高的学生的名字?

sql - Oracle Merge 语句中的 Column ambiguously defined 错误

mysql - SQL 查询每个用户购买产品的概览

php - 将排名值添加到我的 MySQL 表