✅ EntityFramework Core trying to add Navigation Property that already exists
I'm getting this fault:
Entity class:
The owners property linked:
The model builder:
15 Replies
The code that triggers the error:
I suspect the Owners = new List<ApplicationUser> { user } is causing it by trying to add a new entry into the AspNetUsers table instead of adding the Id into navigation table.
I suspect that is exactly what's happening too
How do i force it to only focus on linking the ids?
Is EF tracking disabled? The code seems to be correct, because you are using the existing user, queried by
_userManager.GetUserAsync(principal)
. This should be already attached to the context, which means that it should not be treated as a new entry (e.g. Owners = new List<ApplicationUser> { user }})
)that call is actually within another function. I added it for clairity. I'll try integrating it
ya no luck
same issue
and i dont think tracking is disabled. I used AsNoTracking only for the plans data
ok, I added:
and that worked.
Users is the DbSet<ApplicationUser> property
heavy-handed, but it worked
Great you figured it out, I would still like to know why the initial solution didn't work
ya, same
maybe using the UserManager doesn't cause the value to be tracked?
try to add the following after you select the user with the userManager:
_dbContext.Database.Attach(user)
kk
this is how you manually attach untracked entities to the context
it should throw an exception if the entity is already tracked
ohhh, I was calling the user outside of the context
here's the whole method:
this is what it was:
so i was looking for the user outside of establishing the context with the using
one sec, i have to reform the code to test
nvm, issue remains if i move the user call within the using
ah, it's context.Attach(user);
ok, that worked.
Great, it turns out the user had not been tracked by EF
ya, thansk a bunch. Guess UserManager doesn't track at all
$close
If you have no further questions, please use /close to mark the forum thread as answered