.NET 9 - EF Core + Aspire - Database seeding
I've been looking into different ways to seed our database, and there are a lot of conflicting information.
I have a .NET Aspire project, with a BackendService and a MigrationService. I want to seed a bunch of test data into the database if it's not present. I want to do this through EF and not write SQL scripts.
The EF recommendation is using UseAsyncSeeding (as well as UseSeeding?):
https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding#configuration-options-useseeding-and-useasyncseeding-methods
The .NET Aspire docs simply have this:
https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding#configuration-options-useseeding-and-useasyncseeding-methods
I would like for the logic to be seperated from the BackendService, and potentially be an extra worker service that simply adds data to the database, from entities like
SessionEntity
.
Any good repos with examples on how to properly do the seeding? The EF recommendation seems extremely wordy in it's implementation, and I'd like for it to be easy to add to a list of entites you want to seed.Data Seeding - EF Core
Using data seeding to populate a database with an initial set of data using Entity Framework Core
4 Replies
This part of the documentation recommends a seperate MigrationService, yet gives no good examples of how to seed your actual entites. It also doesn't correlate with the EF documentation on using best practices for seeding your data.
https://learn.microsoft.com/en-us/dotnet/aspire/database/ef-core-migrations#remove-existing-seeding-code
Apply EF Core migrations in .NET Aspire - .NET Aspire
Learn about how to to apply Entity Framework Core migrations in .NET Aspire
You might get some inspiration from the ef docs repo.
https://github.com/dotnet/EntityFramework.Docs/tree/main/samples/core/Modeling/DataSeeding
GitHub
EntityFramework.Docs/samples/core/Modeling/DataSeeding at main · d...
Documentation for Entity Framework Core and Entity Framework 6 - dotnet/EntityFramework.Docs
This example does have a basic seed example, in it's
SeedDataAsync
function. I've followed this guide for a project I did and it works fine.I made a cool migration check .