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
show code
$code
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/are you mapping from an EF entity to a domain model and then back to an EF entity
my best guess is that your repo is creating a new dbcontext for each call or something
My bet's on a general clusterfuck that repos introduce
Probably
.AsNoTracking()
or a .Select()
somewhere in the fetching codeannoyingly 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
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
same db context, new entity probably
https://discord.com/channels/143867839282020352/1330365353162969278/1330365353162969278 @Harry this thread might be helpful
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?
Quoted by
<@72080813948153856> from #Updating/Deleting owned properties with EF Core and AutoMapper (click here)
React with ❌ to remove this embed.
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