tl; dr . Check out my dwCheckApi project to find out how I implemented it.
As others have said, you can read your initial data from JSON or similar (this way, if you want, you can control the source code).
The way I implemented this in my projects is to have a method that is called in the Configure method in the Startup class (only at design time):
if (env.IsDevelopment()) { app.EnsureDatabaseIsSeeded(false); }
which causes the following:
public static int EnsureDatabaseIsSeeded(this IApplicationBuilder applicationBuilder, bool autoMigrateDatabase) {
My DbContext is of type DwContext , which is a class extending the EF Core DbContext
The EnsureSeedData extension method is as follows:
public static int EnsureSeedData(this DwContext context) { var bookCount = default(int); var characterCount = default(int); var bookSeriesCount = default(int);
This app is designed to show the relationships between books, characters and TV shows. That is why there are three seeders.
And one of these seeder methods looks like this:
public async Task<int> SeedBookEntitiesFromJson(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException($"Value of {filePath} must be supplied to {nameof(SeedBookEntitiesFromJson)}"); } if (!File.Exists(filePath)) { throw new ArgumentException($"The file { filePath} does not exist"); } var dataSet = File.ReadAllText(filePath); var seedData = JsonConvert.DeserializeObject<List<Book>>(dataSet);
There may be some code here that is not very good, but it can be the starting point for a rebound.
Since seeders are called only in the development environment, you need to make sure that your application starts this way (if you start from the command line, you can use ASPNETCORE_ENVIRONMENT=Development dotnet run to make sure that it starts in development).
It also means that you will need a different approach to populating your database in a production environment. In dwCheckApi, I have a controller that can be called to populate the database (see how I do it, DatabaseController SeedData method ).