记录一条asp.net core 使用ef查询时出现的错误(AsNoTracking()方法)

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

翻译过来就是ef没法同时跟踪两条实体的变化,也就是不能脚踏两条船

解决方法就是使用 AsNoTracking()做查询使用

db.CustomerAddr.AsNoTracking().FirstOrDefault(p => p.CustomerAddrId == addr.CustomerAddrId)
但是因为用的是core做的,所以引用空间时需要引用
using Microsoft.EntityFrameworkCore;

而不是
using System.Data.Entity;

不然会报
Could not load file or assembly ‘System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL’. 系统找不到指定的文件。

而且注意:
使用AsNoTracking()方法注意:
只能用于查询,不能把查询后的实体用作其他的用途,不然会导致其他的错误。例如:我想查询数据库有没有一条数据,用AsNotracking()查询后,如果有就把他赋值给一个实体,如果没有就new一个新实体 。这样的话,因为AsNotracking()没有把这个实体加到EF跟踪里面,EF就会认为这个实体在数据库不存在,就会把查询后的实体添加到数据库,但是实际情况是这个实体是存在于数据库里面的,这样就会报数据重复的错误。所以使用AsNotracking()只能用于查询,不能用于其他赋值的操作。

参考文章:
https://blog.csdn.net/chengmin1989/article/details/88941525

https://blog.csdn.net/CherishTheYouth/article/details/97730587

猜你喜欢

转载自blog.csdn.net/weixin_44517477/article/details/106639569
今日推荐