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
new Industry(149)
, butdb.Find(149)
or similar. Or assignnull
to nav property and set the exposed explicit FK property.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.