C
C#2d ago
Harry

Entity Framework Tracking not making changes to db

hoping someone can explain what im doing wrong i have a method that fetches all entities that i need into a list<entity> this data is then returned to a variable in my business logic layer then i loop over those entities perform an action for each of those pieces of data after doing that call another repo method that sets a processed flag to true and saves changes doing this when i would save changes, I would get an error about the entity already being tracked when making the update, or it would go through and no change would be made. I hope thats enough context for someone to atleast have an idea of what might be going on.
10 Replies
Keswiik
Keswiik2d ago
show code $code
MODiX
MODiX2d ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
mg
mg2d ago
are you mapping from an EF entity to a domain model and then back to an EF entity
Keswiik
Keswiik2d ago
my best guess is that your repo is creating a new dbcontext for each call or something
Angius
Angius2d ago
My bet's on a general clusterfuck that repos introduce Probably .AsNoTracking() or a .Select() somewhere in the fetching code
Harry
HarryOP2d ago
annoyingly i cant post the code as its on my work pc sorry. i understand that limits the help possible, im just hoping for some nuggets of knowledge that can point me in the right direction on monday
Keswiik
Keswiik2d ago
my guess is business layer -> repo with tracking, maybe dbcontext isn't disposed of so it doesn't get GC'd business layer does shit with models business layer -> repo to save, attempt to track them with a new dbcontext blow up because first context is still floating around and tracking them
mg
mg2d ago
same db context, new entity probably https://discord.com/channels/143867839282020352/1330365353162969278/1330365353162969278 @Harry this thread might be helpful
MODiX
MODiX2d ago
y4hira
The problem I'm facing is that automapper is not tracking the changes since when i retrive AsNotracking() it wont change anything, but if i remove that, then it complains about the same entity being tracked when i do mapper.map<Entity>(doman), which creates a new entity and EF begins tracking it, I solved it by fetching the entity in the repository and doing mapper.map(entity, domain) so it replaces the one i fetched, but in my command handler I already did the fetch of the entity and did an in place mapping to change its values, how can I avoid re fetching in my repository?
React with ❌ to remove this embed.
Harry
HarryOP2d ago
great thanks guys ill look into all this. if i make the changes in the original query that fetches the entities, all works fine. so its something when passing the entities back to the business layer and then back down to the repo layer

Did you find this page helpful?