1
Theinstanceofentity type'CodingRule'cannotbetrackedbecauseanotherinstancewiththesamekeyvaluefor{ld'}isalreadybeingtracked.Whenattachingexistingentities,ensurethatonlyoneentityinstance with a givenkeyvalue is attached. Consider using'DbContextOptionsBuilder.EnableSensitiveDataLogging'toseetheconflictingkeyvalues.

这个错误提示 The instance of entity type 'CodingRule' cannot be tracked because another instance with the same key value for '{ld}' is already being tracked 意味着你的 DbContext 实例中已经有一个具有相同主键值的 CodingRule 实体在被跟踪,因此无法再次跟踪相同主键值的另一个 CodingRule 实体。

解决办法:

在后端更新时,重新刷新UI

1
2
3
//重新刷新UI
StateHasChanged();
//测试后没用,因为只涉及到UI的

·········没用

———-2024.8.14更新

1
2
3
4
5
6
7
8
9
10
11
          
//更新前查询要更新的实体是否已经被跟踪
var existingEntity = _context.ChangeTracker.Entries<CodingRule>()
.FirstOrDefault(e => e.Entity.Id == codingRule.Id)?.Entity;

//如果已跟踪
if (existingEntity != null)
{
//将状态设置为分离
_context.Entry(existingEntity).State = Microsoft.EntityFrameworkCore.EntityState.Detached;
}