duplicate key error efcore
I'm trying to use efcore but I'm getting a
duplicate key value violates unique constraint "PK_Tags"
error.
My model contains:
however, this is not a key?
I'm updating the value by getting it from the database, modifying it, then calling Update with the modified value.16 Replies
Check your database schema. My guess is that
Tags
is being mapped to a new table.Is keeping entries I got from the database around for a long time bad?
long time as in across dbcontexts
in other words, if I get value
a
from dbctx1
, then cache a
, dispose of dbctx1
, create dbctx2
, and use the .Update method on dbctx2
with value a
I'm guessing it is a problem, and that the changetracker of dbctx2 doesn't recognize a
as being modified, rather created
if that's the case, am I supposed to do a new query everytime I use a new dbcontext? isn't that inefficient?
ping for visibilityFirst off, did you look at your DB schema?
I've come to the conclusion that this is most likely unrelated
And you can keep entries around for a long time, I have caches like that in some of my projects.
Not sure whether or not that's recommended, though.
the sql states an INSERT INTO instead of the UPDATE I expect when using .Update
show actual code
I have a service injecting an IMemoryCache, then have a get method:
after which a second call to this gets the value from cache instead of db, and then I call this:
on the second context
which then causes an error
Show the code that calls
Update
I wonder if
db.Tags.Update(value).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
would workYou could also try tracking the entity before modifying it
is there a way to make it track something?
That's what
DbSet.Update
does
it begins tracking an entity and sets the state to modified
So I'd try calling DbSet.Update
with your tag, modify the tag after, then call SaveChanges
I was wondering if I could start tracking if I can get it from the cache
So call
DbSet.Update
on your tags every time you load from the cache....?but it's never modified
so I was concerned the setting state to modified would break things
found .Attach
seems to do that
did not work
got it working
I was being stupid
thanks for dealing with it :catlaugh: