InvalidOperationException: The instance of entity type ‘AwordDeclare’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.
无法跟踪实体类型’AwordDeclare’的实例,因为已经跟踪了另一个具有相同’{‘Id’}键值的实例。 附加现有实体时,请确保仅附加一个具有给定键值的实体实例
考虑使用’DbContextOptionsBuilder.EnableSensitiveDataLogging’来查看冲突的键值。
efcore 默认跟踪实体,你再次跟踪相同的实体,回出现该问题
这时候怎么办呢?(推荐使用第二种)
- 可以在查询的时候加入AsNoTracking()方法,这个方法表示取消跟踪
- 全局配置,修改efcore 的默认配置,取消跟踪实例
在Startup.cs文件中的ConfigureServices方法中加入
string ProductQualityContext_SERVER_CONN = Configuration.GetConnectionString("ProductQualityContext_SERVER_CONN");
services.AddDbContext<ProductQualityContext>(opt =>
{
opt.UseSqlServer(ProductQualityContext_SERVER_CONN, b => b.EnableRetryOnFailure().CommandTimeout(60)); //注入数据库连接字符串//
opt.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);//解决跟踪同一个ID问题
});
当你配置好后,一般就可以了,如果还是回出现上面的情况,这就不是efcore的问题,可能是你整个项目的架构又问题
- 你项目是否使用的是单列模式:单列模式所有的用户进来使用的是同一个上下文
我们每次操作数据时,讲究上下文唯一,但每次,不同用户进来都是一个上下文时,是不是感觉有点怪,我们追求的上下文唯一不应该是单次操作数据保证数据的唯一吗。
如果是单列模式,换一个模式吧,应该就解决该问题了, - 或许是其他造成的
如果还是不行,博主我以不知道了。没有怎么深究