C#C
C#3y ago
joren

Data seeding database

So currently in my program.cs I have the following code:

// Seed the database, disable once done.
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        DataContext context = services.GetRequiredService<DataContext>();
        
        if(context.Database.EnsureCreated())
        {
            var dataSeeder = new DataSeeder(context);
            dataSeeder.SeedData();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error occurred while seeding the database: {ex.Message}");
    }
}


Now, seeding only makes sense in a development environment and only has to be executed once. So would this be a proper way to go about it? My DataSeeder class basically creates objects of all my models, gives them mock values, and that I save to the database.
Was this page helpful?