C#
C#

help

Root Question Message

Ysehporp
Ysehporp1/30/2023
❔ 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?
Ysehporp
Ysehporp1/30/2023
To clarify, the data is seeded in (and is retreivable) properly but my first attempt to add data after seeding always results in failure.
Ysehporp
Ysehporp1/30/2023
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
jalepi1/30/2023
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
Ysehporp1/30/2023
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
jalepi1/30/2023
I assume your database table and your data model entity are both configured as auto increment, right?
Ysehporp
Ysehporp1/30/2023
Hmmm perhaps not. Do I need a special attribute tag or something?
jalepi
jalepi1/30/2023
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.
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy