EF更新报错 tracked because another instance with the same key value

创建了多个实体对象,但他们的主键是一样的,更新时会报异常

EF更新时报错:出现这种原因是因为两个不同的对象使用了同一个id值
The instance of entity type 'XXX' cannot be 
tracked because another instance with the same key value for {'XX'} is already being tracked.

//解决办法1:
更新前请调用:表Repository.Instance.Detached(对象)或repository.Detached(对象)
或清除所有跟踪(注意需要写在savechange调用后或者代码的操作数据库前):repository.DbContext.ChangeTracker.CascadeChanges();

//解决办法2,查询时设置不跟踪
var data = repository.DbContext.Set<>().AsNoTracking().Where(x => 条件).FirstOrDefault();
//或者查询后取消实体跟踪repository.Detached(data)
Last Updated 2025/11/30 11:33:23