❔ Entity Framework duplicating primary key with seeded data.
I have set up a database with EF6 and as part of verifying that it is working I have seeded in some data. The problem is, when I try to add data from those classes with auto incrementing keys the code attempts to start at id=1 instead of id=6 to position itself after my seeded data. It throws an error complaining about being unable to save data because of a duplicate primary key. How can I force it to respect my seeded data?
7 Replies
To clarify, the data is seeded in (and is retreivable) properly but my first attempt to add data after seeding always results in failure.
Okay. I solved this really inelegantly where I created a manual query to find the last id and add that way. However, this means i load the entire message history of every user on my platform every time I want to add a new message, which is really not what I want. Can anyone suggest a way I might optimize this interaction?
If your table has auto increment id, you probably should not inform any id in your seed data while inserting data, only when updating.
I'm not sure im understanding you correctly so correct me if I am but currently I dont explicity inform any id in my seed data, i just let it auto assign them
I assume your database table and your data model entity are both configured as auto increment, right?
Hmmm perhaps not. Do I need a special attribute tag or something?
It's necessary that both your table AND your data model entity are configured properly.
Database, it is specific, you should check their docs.
EF is pretty straight forward as well, using model creation with fluent API, or attributes. Also, check their docs.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.