我正在从表FattureFornitori
中检索实体列表,并还加载它们所拥有的集合(Voci,复数形式-Voce,单数形式)以及从每个Voce
到TipoCosto
实体的引用:
var db = new DbGestPre();
db.Configuration.ProxyCreationEnabled = false;
var s = db.FattureFornitori
.Include(x => x.Voci)
.Include(x => x.Voci.Select(y => y.TipoCosto))
.AsNoTracking().ToList();
现在,单个Voci
中的多个FattureFornitori
可以引用相同的TipoCosto
。因此,当我尝试使用其Voci和引用的FattureFornitori
附加单个TipoCosto
时,遇到以下错误:
System.InvalidOperationException: 'Attaching an entity of type 'GP.Model.TipoCosto' 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.'
对该FattureFornitori实体(在此处名为ff的一些调试,显示:
ff.Voci[1].IdTipoCosto == ff.Voci[0].IdTipoCosto
true
ff.Voci[1].TipoCosto == ff.Voci[0].TipoCosto
false
所以实体框架为同一实体创建多个实例!因此,attach方法引起的错误是有道理的。但是如何解决这种情况呢?我照顾了GraphDiff和其他类似工具,但它们无济于事。有什么提示吗?谢谢!!
我正在从表FattureFornitori中检索实体列表,并还加载它们拥有的集合(Voci,复数形式-Voce,单数形式)以及每个Voce对TipoCosto的引用...