关于EF Core中同一个实体被多次tracked的问题

本文探讨了在Entity Framework Core中遇到的实体重复跟踪错误,特别关注一对多关系中的外键引发的问题。作者通过实例分析了一个Point与Device的复杂关联,展示了如何通过`AsNoTracking()`和设置关联实体为null来避免跟踪冲突。

先来看一段错误提示:The 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.
这里面的"XXXX"可能是任意一个实体模型的名称,“Key"则是这个实体的Key字段。
出现这个错误的原因是试图更新某个实体时,拥有相同Key的另一个实体也被EF Core tracked了。看一下这段代码:

[HttpPost]
public async Task<IActionResult> TestTracked(DeviceType deviceType)
{
    try
    {
    	//type这个实体被EF Core tracked
        var type = await context.DeviceTypes.FindAsync(deviceType.Id);
        //准备更新deviceType实体,但type实体的key与deviceType的key相同,也就是同一个Key的实体被多次tracked,出现本文开头说的错误
        context.Update(deviceType);
        await context.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    return new JsonResult(new { success = true });
}

要解决这个问题很简单,从linq查询返回实体时指定不跟踪实体就行了。

//把原来的代码:var type = await context.DeviceTyp
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值