C# EF The instance of entity type ‘EqInfo‘ cannot be tracked because another instance with the

1 篇文章 0 订阅
1 篇文章 0 订阅

问题详细:"The instance of entity type 'EqInfo' cannot be tracked because another instance with the same key value for {'EqId'} 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."

我是在更新数据的时候出现的,按我想的是:我是更新数据,按道理不存在违反数据库中的主键唯一性,但是确实报了错。

问题是出现在EF上了,网上提到在startup.cs文件中修改连接上下文如下,禁用掉跟踪The instance of entity type 'manager' 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 ent - 清枫塞子 - 博客园 (cnblogs.com)https://www.cnblogs.com/jie566/p/11447869.html

services.AddDbContext<Context>(options =>
options.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));

感觉不是那么好,只是回避了问题,而不是理解和解决,进一步搜索The instance of entity type 'Menu' cannot be tracked because another instance with the same key v... - osc_69808867的个人空间 - OSCHINA - 中文开源技术交流社区https://my.oschina.net/u/4871714/blog/4928063

 找到问题所在,因为我在更新数据时,有些字段是不能够让用户修改的,我就没有把这些字段放到表单中,那就要求在后台收到表单数据后,查询数据库把缺失的数据补全,,然后就出现问题了

就是说我在执行更新操作前又查询了被更新的数据,EF同时跟踪了两个相同ID的实体,就出现了这个问题

解决方案:一种是避免出现上述情况,二是在另一次查询时阻止跟踪,即在查询的语句上加上.AsNoTracking();

特此记录,以备后来!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值