0

I simply want to update an industry property of a client object. To do so, I retrieve the client from the DB using a repository. This would result in my industry (example id:149) being tracked.

            var client = await _clientRepository.GetAsync(request.ClientId, token);
            ind = _db.ChangeTracker.Entries<Industry>().Count();

Then, I update the industry by calling SetIndustry with a new Industry with Id:149 (same as before).

            client.SetIndustry(new Industry(149)); 
            ind = _db.ChangeTracker.Entries<Industry>().Count();

At this point EF Core 2.1 throws an exception.

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

In this class I cannot access the DBContext so i can't play with the change tracker. I was wondering how I could work around this problem?

Thx Seb

3
  • 1
    It's hard to give you a good advice since you are self limiting with these "repositories". EF context gives you a great control - tracking / no tracking queries, eager loading or not etc. The repository (anti)pattern might work for simple things, but definitely fails with relationships. From EF perspective you shouldn't use new Industry(149), but db.Find(149) or similar. Or assign null to nav property and set the exposed explicit FK property.
    – Ivan Stoev
    Aug 23, 2018 at 10:14
  • Actually we are following DDD principles we are retrieving our aggregate using this repository. The save method of this same repo does way more than just save to db. That's why we have to do that...
    – Seb
    Aug 23, 2018 at 11:18
  • I was suspecting DDD here - constructor with parameter, SetIndustry method etc. Just another source of problems. Simply don't mix the domain model with persistence model - they have different requirements. Or in other words, don't use domain model as storage model. Create separate models, do the mappings between the two where needed. The store model should not contain any business / domain logic - simple POCO classes with public parameterless constructors and public auto get/set properties. No methods. No special getter/setters. No unmapped stuff. No OOP.
    – Ivan Stoev
    Aug 23, 2018 at 11:33

1 Answer 1

0

I just added AsNoTracking() to my document object when I created my document variable and it worked out. Try doing the same with your client object.

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.