.NET Core-EF-无法跟踪实体类型“ User”的实例,因为已经跟踪了另一个键值为“ {Id:1}”的实例

时间:2020-09-07 11:54:44

标签: entity-framework

我知道已经有关于此问题的答案,但到目前为止,它们都没有起作用

EF不断返回错误:

The instance of entity type 'User' cannot be tracked because another instance with the key value '{Id: 1}' is already being tracked.
  • 尽管我使用QueryTrackingBehavior.NoTracking禁用了跟踪功能
  • 我尝试了 _context.Entry(user).State = EntityState.Detached;
  • 我也尝试过
    services.AddDbContext<SomeDBContext>(opt => 
        opt.UseSqlServer(Configuration.GetConnectionString("***********"))
           .EnableSensitiveDataLogging()
           .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)

我什至不知道哪一行会产生错误

[HttpPost]
public async Task<ActionResult<int>> PostPartner(PartnerCreation partnerCreation)
{
       _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        _context.ChangeTracker.AutoDetectChangesEnabled = false;

        var user = await _context.Users.FindAsync(1);

        _context.Entry(user).State = EntityState.Detached;

       if (user == null)
       {
            return NotFound();
       }
       else
       {
            partnerCreation.Partner.Id = partnerCreation.Partner.Id > -1 ? partnerCreation.Partner.Id : null;
            partnerCreation.Manager.Id = partnerCreation.Manager.Id > -1 ? partnerCreation.Manager.Id : null;
            partnerCreation.Partner.retributionPlan.Id = partnerCreation.Partner.retributionPlan.Id > -1? partnerCreation.Partner.retributionPlan.Id : null;
            partnerCreation.Partner.retributionPlan.PartnerId = partnerCreation.Partner.retributionPlan.PartnerId > -1 ? partnerCreation.Partner.retributionPlan.PartnerId : null;
            partnerCreation.Partner.ModificationUser = user;
            partnerCreation.Partner.ModificationDate = DateTime.Now;
            foreach (ProductRetributionData data in partnerCreation.Partner.retributionPlan.ProductRetributionData)
            {
                 data.Id = null;
            }
            partnerCreation.Partner.CreationDate = DateTime.Now;

            _context.Partners.Add(partnerCreation.Partner);
            _context.Users.Add(partnerCreation.Manager);
            await _context.SaveChangesAsync();

            return partnerCreation.Partner.Id;// CreatedAtAction("GetPartners", new { id = partner.Id }, partner);
     }
}

感谢您对此的帮助

0 个答案:

没有答案