gpt4 book ai didi

c# - 附加类型为 'X' 的实体失败,因为同一类型的另一个实体

转载 作者:可可西里 更新时间:2023-11-01 02:59:26 25 4
gpt4 key购买 nike

我在我的代码中偶然发现了一个奇怪的错误。以前可以,但现在有时可以。

我正在使用 EF6 编辑具有某些关系的实体。为了不编辑我“附加”它们的关系(参见示例代码)。

public void EditA(A ThisIsA, B ThisIsB)
{
using (var Context = new LDZ_DEVEntities())
{
Context.As.Attach(ThisIsA);

var b = Context.Bs.FirstOrDefault(x => x.BId == ThisIsB.BId);
//var b = Context.Bs.Find(ThisIsB.BId);

if (b != null)
Context.Bs.Attach(b);
else
b = ThisIsB;

if (b.C != null)
Context.Cs.Attach(b.C);

ThisIsA.Bs.Add(b);

Context.SaveChanges();

}
}

为了简单起见,我已经编辑了名称。

下一行

Context.Cs.Attach(b.C);

抛出这个错误:

Attaching an entity of type 'C' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

引入这一行是因为所有的 C 实体都是静态实体。我从不想创建 C。如果我删除这一行,每次我都会在 A 中添加一个 B;创建了一个 C。这是不可取的。

额外信息:
A 有 B 的列表
B有一个C

此 EditA() 方法在我的软件中的多个位置被调用。只有在循环(导入)中调用该方法时才会出现此错误。在处理第一个记录时没有问题。但是我在第一个记录之后发现了错误。

我已经阅读了这些问题和答案,但它们对我不起作用:

  1. ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

  2. Attaching an entity of type failed because another entity of the same type already has the same primary key value

最佳答案

我修好了。

在 Fabio Luz 的回答中,他说:

//if A has been loaded from context
//dont attach it
//if it has been created outside of the context
//Context.Entry(ThisIsA).State = EntityState.Modified;

这让我开始思考,所以我将代码编辑为:

public void EditA(A ThisIsA, B ThisIsB)
{
using (var Context = new LDZ_DEVEntities())
{
var a = Context.As.Find(ThisIsA.AId);

//var b = Context.Bs.FirstOrDefault(x => x.BId == ThisIsB.BId);
var b = Context.Bs.Find(ThisIsB.BId);

if (b != null)
Context.Bs.Attach(b);
else
b = ThisIsB;

if (b.C != null)
Context.Cs.Attach(b.C);

a.Bs.Add(b);

Context.SaveChanges();

}
}

变更摘要:

  • 将 FirstOrDefault 更改为查找
  • 从上下文中获取 A

一开始我去掉了C的Attach,结果这创建了一个新实体。所以我撤销了这个更改。

特别感谢 Fabio Luz。没有你的帮助,我不可能做到这一点!

关于c# - 附加类型为 'X' 的实体失败,因为同一类型的另一个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350058/

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