C
C#2y ago
Ysehporp

❔ 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
Ysehporp
YsehporpOP2y ago
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?
jalepi
jalepi2y ago
If your table has auto increment id, you probably should not inform any id in your seed data while inserting data, only when updating.
Ysehporp
YsehporpOP2y ago
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
jalepi
jalepi2y ago
I assume your database table and your data model entity are both configured as auto increment, right?
Ysehporp
YsehporpOP2y ago
Hmmm perhaps not. Do I need a special attribute tag or something?
jalepi
jalepi2y ago
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.
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server