gpt4 book ai didi

.net - 异常 :The object cannot be attached because it is already in the object context

转载 作者:行者123 更新时间:2023-12-05 00:13:10 25 4
gpt4 key购买 nike

我正在尝试使用 Entity Framework 在循环中更新记录,如下所示:

var data = userDetails.users.Where(x => x.IsAnonymous == true);

foreach(var item in data)
{
var updatedData = db.Users.FirstOrDefault(x => x.UserId == item.UserId);
updatedData.IsAnonymous = true;
db.Users.Attach(updatedData);
db.ObjectStateManager.ChangeObjectState(updatedData, EntityState.Modified);
db.SaveChanges();
}

虽然附加( db.Users.Attach(updatedData); )我有异常(exception)

The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state



我该如何解决这个错误?

最佳答案

如果这一切都发生在单个 DbContext 的上下文中(或 ObjectContext) - 只需选择记录,更新您想要的字段,然后继续。更新所有记录后 - 然后 调用 .SaveChanges()一次。不需要 AttachChangeObjectState打电话……

var data = userDetails.users.Where(x => x.IsAnonymous == true);

foreach(var item in data)
{
var updatedData = db.Users.FirstOrDefault(x => x.UserId == item.UserId);

if(updatedData != null)
{
updatedData.IsAnonymous = true;
}
}

db.SaveChanges();

由于您刚刚选择了 updatedData来自 db.Users数据集 - 它已经是对象集的一部分 - 无需再次附加它!只需更新您需要的内容,然后调用 .SaveChanges() (最好是整批一次——而不是每条记录一次......)

关于.net - 异常 :The object cannot be attached because it is already in the object context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305353/

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