EF Core报CollectionReport实体已被相同键值实例跟踪错误如何解决
问题原因
这个错误是EF Core变更跟踪器的冲突导致的,根本原因是同一个DbContext实例中同时存在两个主键PaymentRefNumber取值相同的CollectionReport实体实例,其中一个已经被跟踪,另一个尝试被附加时触发了冲突。
具体触发路径:
- 你通过
_collectionReportRepository.GetAll().FirstOrDefaultAsync(...)查询得到的collectionReport默认是跟踪状态,已经被当前DbContext的变更跟踪器托管 - 调用
SplitExtensions.FromSplitCollectionsToCollections生成childCollections时,要么直接把已经跟踪的collectionReport实例加入了待新增的子集合列表,要么在逻辑中新创建了一个PaymentRefNumber和上述实例完全相同的CollectionReport实例 - 执行
SaveRangeAsync时,内部调用的AddRangeAsync会尝试把列表内所有实体都设置为Added状态附加到上下文,遇到重复主键的已跟踪实例就抛出错误
解决方案
你可以按优先级选择以下修复方案:
- 优先修复转换逻辑:检查
SplitExtensions.FromSplitCollectionsToCollections方法,确认返回的childCollections列表里只包含需要新增的子CollectionReport实例,不要把已经存在的主collectionReport实例加入待新增列表。如果是子实例关联主实例的导航属性时新创建了主实例对象,改成直接赋值已经跟踪的collectionReport实例,或者仅给子实例的主表外键字段赋值即可,不要新构造同主键的主实体对象。 - 查询时关闭跟踪(可选):如果主
collectionReport只需要做更新操作,可以在查询的时候加AsNoTracking(),避免提前被跟踪,更新的时候手动设置实体状态:// 修改查询逻辑 var collectionReport = await _collectionReportRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(c => c.PaymentRefNumber == split.PaymentReferenceNumber); // 更新时手动指定状态 collectionReport.IsSplitted = true; _collectionReportRepository.Entry(collectionReport).State = EntityState.Modified; await _collectionReportRepository.UpdateAsync(collectionReport); - 临时剥离跟踪(不推荐):如果不方便修改转换逻辑,可以在调用
SaveRangeAsync前把已经跟踪的主实例剥离跟踪:await _collectionReportRepository.UpdateAsync(collectionReport); // 新增这行剥离跟踪 _collectionReportRepository.Entry(collectionReport).State = EntityState.Detached; var splitCollections = await GetSplitCollectionReportsByPayRef(split.PaymentReferenceNumber); var childCollections = SplitExtensions.FromSplitCollectionsToCollections(splitCollections, collectionReport); await _collectionReportRepository.SaveRangeAsync(childCollections);
内容的提问来源于stack exchange,提问作者Thokem
相关产品推荐
相关产品推荐

