首页 > 其他分享 >The instance of entity type 'xxx' cannot be tracked because another instance with the same

The instance of entity type 'xxx' cannot be tracked because another instance with the same

时间:2024-10-16 13:49:16浏览次数:1  
标签:dto tracked xxx db 查询 instance CheckProductionCode

发生的原因,在CheckProductionCode()方法中根据主键id查询对象时没有使用AsNoTracking(),示例:_db.Productions.AsNoTracking()
那么EF会把查询出的对象缓存并跟踪对象状态,之后再Update的时候就会查询现有已跟踪的对象,发现已经存在一个相同主键的对象,所以报错。

 /// <summary>
 /// 编辑修改商品
 /// </summary>
 /// <param name="dto"></param>
 /// <exception cref="Exception"></exception>
 public void EditProduction(Production dto)
 {
     bool res = CheckProductionCode(dto);
     if (!res)
     {
         throw new Exception("商品编码重复");
     }
     _db.Productions.Update(dto);
     _db.SaveChanges();
 }

CheckProductionCode

 public bool CheckProductionCode(Production dto)
 {
     var res = _db.Productions.Where(x => x.ProductionId == dto.ProductionId).FirstOrDefault();
     //....
     return true;
 }

解决办法1:查询的时候禁用状态跟踪 _db.Productions.AsNoTracking()
解决办法2:在Program.cs中配置数据库的时候,设置所有查询禁用跟踪

// 使用 Pomelo.EntityFrameworkCore.MySql
builder.Services.AddDbContext<DataMgrContext>(opt =>
{
    string connStr = builder.Configuration.GetConnectionString("MysqlContext") + "";
    var serverVersion = ServerVersion.AutoDetect(connStr);
    opt.UseMySql(connStr, serverVersion);
    //重要,不跟踪查询得到的实体。
    opt.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});

 

标签:dto,tracked,xxx,db,查询,instance,CheckProductionCode
From: https://www.cnblogs.com/xsj1989/p/18469788

相关文章