我知道已经有关于此问题的答案,但到目前为止,它们都没有起作用
EF不断返回错误:
The instance of entity type 'User' cannot be tracked because another instance with the key value '{Id: 1}' is already being tracked.
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);
}
}
感谢您对此的帮助