实体框架6-附加通过AsNoTracking查询的实体图

问题描述 投票:0回答:1

我正在从表FattureFornitori中检索实体列表,并还加载它们所拥有的集合(Voci,复数形式-Voce,单数形式)以及从每个VoceTipoCosto实体的引用:

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的引用...

.net sql-server entity-framework entity-framework-6 ef-code-first
1个回答
0
投票
如Gert Arnold所建议,一种解决方法是删除AsNoTracking()。但这意味着数据库上下文会将所有实体添加到被跟踪的实体中,因此会导致性能下降。
© www.soinside.com 2019 - 2024. All rights reserved.