csharp EF Core 同一个实体被多次 tracked

csharp EF Core 同一个实体被多次 tracked

具体体现为:

he instance of entity type ‘XXXX’ cannot be tracked because another instance with the same key value for {‘Key’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

原因:在使用 ef 查询后,再使用 ef 更新参与了查询的实体,就会报此错误。

重现

1
2
3
4
5
6
7
8
9
10
// _selectedCategory 是 db.Category 里的一个实例

var relatedDevices = db.Devices
.Include(d => d.Category)
.Where(d => d.Category == _selectedCategory)
.ToList();


db.Categories.Remove(_selectedCategory);

解决:AsNoTracking

1
2
3
4
5
6
7
8
// 下面位置添加 .AsNoTracking()

var relatedDevices = db.Devices.AsNoTracking()
.Include(d => d.Category)
.Where(d => d.Category == _selectedCategory)
.ToList();

db.Categories.Remove(_selectedCategory);

csharp EF Core 同一个实体被多次 tracked
https://taylorandtony.github.io/2025/02/02/csharp-EF-Core同一个实体被多次tracked/
作者
TaylorAndTony
发布于
2025年2月2日
许可协议