2 years ago
#41242

Markus S.
Entity Framework Core seed data only if it does not exist
Entity Framework Migrations provide a way to seed data along with the creation of the table by using .HasData() on the Entity Type. This will translate into a Migration with calls to MigrationBuilder.InsertData to insert the data when the migration runs. It works fine when the data in the table is only provided by the migration. However when the seeded data is already available in the table, the migration fails with a Duplicate Key error because the keys it tries to insert are already present.
I know i can write a database initializer method just making use of Entity Framework and provide the data outside the migrations.
I also know that i can run a native SQL statement including a check if the data exists and inserting it only in this case as part of the migration.
But i'm a bit surprised that this (IMHO not so exotic) feature does not exist.
Or is there something i might have been missing and there is a way to configure an entity to provide seed data only if there is no data present in the table? (which is the purpose of this question)
Update: We are using Entity Framework 3.1.22
entity-framework-core
entity-framework-migrations
seeding
0 Answers
Your Answer