Anthony Fleury
Anthony Fleury

Reputation: 115

Is it possible to seed data with specific identifier using EF Core custom initialization logic?

Using EntityFramework Core 7.0, I would like to seed some data while being able to specify identifiers (primary keys) for the records to create.

As this seeding is needed for integration testing purposes and the database is only created once, I cannot use the .HasData() method inside the OnModelCreating function of my database context (as suggested in the documentation).

This section of the documentation suggests using custom initialization logic.
This is exactly what I need to be able to seed data again after each test.
However, I could not find any clean way to be able to also provide identifiers for my records using this method.

I managed to solve my problem in a way that I don't particularly like and would like to know if there is a cleaner way.

Simplified code sample of my temporary working solution:

context.Database.BeginTransaction(System.Data.IsolationLevel.Unspecified);

context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Notification ON");

await context.Notification.AddRangeAsync(data);

context.SaveChanges();

context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Notification OFF");

context.Database.CommitTransaction();

Many thanks!

Upvotes: 2

Views: 150

Answers (1)

Anthony Fleury
Anthony Fleury

Reputation: 115

One easy way to solve this issue is to use the SQL command SET IDENTITY_INSERT:

context.Database.BeginTransaction(System.Data.IsolationLevel.Unspecified);

context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Notification ON");

await context.Notification.AddRangeAsync(data);

context.SaveChanges();

context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Notification OFF");

context.Database.CommitTransaction();

Upvotes: 0

Related Questions