数据库数据修改报错The instance of entity type ‘XXX‘ cannot be tracked

在数据库更新时,
1 首先查找数据库是否包含该项
2 然后更新该项目获添加,
在先查找的时候已经跟踪数据
第二步插入会报错The instance of entity type ‘XXX’ cannot be tracked

这里使用的是Microsoft.EntityFrameworkCore的数据库DbContext

using (YieldInfoDatabase context = new YieldInfoDatabase() { Path = SysStatus.ProductPath })
                {
                    try
                    {
                        context.Database.EnsureCreated();
                        foreach (var data in datalist)
                        {
                            
                            var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime).ToList();//这里先查找了数据已经将对应数据放入缓存跟踪,所以就报错
                            context.Entry(data).State = (records?.Count ?? 0) > 0 ?
                                EntityState.Modified : EntityState.Added;
                        }

                        context.SaveChanges();
                        return EmRes.Succeed;
                    }
                    catch (Microsoft.Data.Sqlite.SqliteException ex)
                    {
                        Logger.Error($"写入数据失败{ex.ToString()}");
                        return EmRes.DbWriteErr;
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"写入数据失败{ex.ToString()}");
                        return EmRes.DbWriteErr;
                    }
                }

以上代码会报错:

System.InvalidOperationException:“The instance of entity type ‘XXX’ cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.”

var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime).ToList();
这里先查找了数据已经将对应数据放入缓存跟踪,所以就报错
应该修改为
var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime ).AsNoTracking().ToList();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值