gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:38:12 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com