2

I am getting changed entity from fronted, mapping it on backend side and simply want to update it in database. Update is performing like this:

[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();
        }}

Before this action, i am getting the list of users and sending it to frontend. Although I set QueryTrackingBehavior to NoTracking, i am getting exception:

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.'

Where Contract is related entity for Worker which is updated...

Any idea what i am doing wrong here?

UPDATE:

Worker - Contract relation:

   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; }
}
5
  • Would you please provide the code for Worker and Contract models in the question? Jul 17, 2018 at 8:30
  • i've updated the question, thx
    – zlaayaa
    Jul 17, 2018 at 8:47
  • Still you question is incomplete! Where is your IId base class? Why did you omit the other properties of the Worker and Contract classes? Jul 17, 2018 at 8:50
  • It's just an interface with Id property, and another properties are just simple strings
    – zlaayaa
    Jul 17, 2018 at 8:52
  • Okay..See my answer below..I have already answered your question. Jul 17, 2018 at 8:54

1 Answer 1

1

Okay! got the problem in your code. You didn't map the updated entity to the existing entity that you pulled from the database. You have to map the updated entity to the existing entity. To do so you can use AutoMapper or explicit mapping as follows:

You can solve the problem as follows:

[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();
        }
 }

Alternatively you can try as follows:

[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();
      }
}
7
  • Ok, so if i have for example 10 more properies, i will have to remap them manually? Or to use automapper...?
    – zlaayaa
    Jul 17, 2018 at 9:22
  • Is there any other way or i have to check every single property if it's changed?
    – zlaayaa
    Jul 17, 2018 at 10:16
  • You can use both. But I personally prefer AutoMaper to minimize the lines of code. Jul 17, 2018 at 10:23
  • I tried with automapper, with entity = _mapper.Map<Worker>(workerDto), but ef core can not see changes in entity...
    – zlaayaa
    Jul 17, 2018 at 10:28
  • 1
    SOLVED Might be helpful to someone who encounter the same problem. I tried to update everything from parent entity, making queriable if it exist first. In that part, EF Core start with tracking, and when i try to update related data, it is already tracked. No need for that, you can find it by context.Entity.Find(id). Also, when you want to update parent entity in a way that you want to delete one of it's related collection items, do that in that specific child entity, and database will just set null for that deleted child(with assumption you declared that relation in OnModelCreating() method.
    – zlaayaa
    Jul 19, 2018 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.