gpt4 book ai didi

postgresql - EF Core 2.0 更新 - 跟踪问题

转载 作者:行者123 更新时间:2023-11-29 12:16:32 26 4
gpt4 key购买 nike

我正在从前端获取更改的实体,将其映射到后端,并且只想在数据库中更新它。更新执行如下:

[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody]Worker worker)
{
using (var dbContext= new MyDbContext())
{
dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

var entity = dbContext.Workers.FirstOrDefault(r => r.Id == worker.Id);

if (entity == null) return BadRequest();

dbContext.Workers.Update(worker);
dbContext.SaveChanges();
return Ok();
}}

在此操作之前,我正在获取用户列表并将其发送到前端。尽管我将 QueryTrackingBehavior 设置为 NoTracking,但出现异常:

System.InvalidOperationException: 'The instance of entity type 'Contract' cannot be tracked because another instance with the key value 'Id:4' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.'

Contract 是更新的 Worker 的相关实体...

知道我在这里做错了什么吗?

更新:

worker -契约(Contract)关系:

   public class Worker: IId
{
public int Id { get; set; }
public ICollection<Contract> Contracts{ get; set; }
}
public class Contract: IId
{
public int Id { get; set; }
public int WorkerId { get; set; }
public Worker Worker { get; set; }
}

最佳答案

好的!在您的代码中遇到问题。您没有将更新的实体映射到您从数据库中提取的现有实体。您必须将更新的实体映射到现有实体。为此,您可以使用 AutoMapper 或如下显式映射:

您可以按如下方式解决问题:

[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody]Worker worker)
{
using (var dbContext= new MyDbContext())
{
var entityToBeUpdated = dbContext.Workers.AsNoTracking().FirstOrDefault(r => r.Id == worker.Id);

if (entity == null) return BadRequest();

entityToBeUpdated.Property1 = worker.Property1;
entityToBeUpdated.Property2 = worker.Property2;
// Do the same for the other changed properties as well

dbContext.Workers.Update(entityToBeUpdated);
dbContext.SaveChanges();
return Ok();
}
}

或者您可以尝试如下操作:

[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody]Worker worker)
{
using (var dbContext= new MyDbContext())
{
var entityToBeUpdated = dbContext.Workers.FirstOrDefault(r => r.Id == worker.Id);

if (entity == null) return BadRequest();

entityToBeUpdated.Property1 = worker.Property1;
entityToBeUpdated.Property2 = worker.Property2;
// Do the same for the other changed properties as well.

dbContext.SaveChanges();
return Ok();
}
}

关于postgresql - EF Core 2.0 更新 - 跟踪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com