Search code examples
asp.net-coreasync-awaitconfigstoreseeding

Change of Program.cs in ASP.NET Core 6 for seedData


I work in ASP.NET Core 6. I have a Json file containing user information to be stored in the database. I also have a class as (SeedUserData) that reads from that json file and stores users one by one in the database.

I want the information from the file to be automatically imported and stored in the database when the program runs, but only if the database is currently empty. How should I modify the program to achieve this?

SeedUserData:

namespace API.Data.SeedData
{
    public class SeedUserData
    {
        public static async Task SeedUsers(DataContext Context,ILoggerFactory logger)
        {
            try
            {
                if (!await Context.Users.AnyAsync())
                {
                    var userData = await File.ReadAllTextAsync("Data/SeedData/UserSeedData.json");
                    var users = JsonSerializer.Deserialize<List<User>>(userData);

                    if (users == null) 
                        return;
             
                    await Context.Users.AddRangeAsync(users);
                    await Context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                var log = logger.CreateLogger<SeedUserData>();
                log.LogError(ex.Message);
            }
        }
    }
}

Solution

  • A nice place to call SeedUsers is in Program.cs:

    app.MapControllerRoute(...
    
    ...
    
    using (var scope = app.Services.CreateScope())
    {
       var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>
    ();
       SeedUserData.SeedUsers(context, ...);
    }
    
    app.Run();
    

    You are already checking if any Users exist in the database, which is good enough. As an extra step you may want to ensure that the database will be created and prepared according to any migrations:

    if (Context.Database.GetPendingMigrations().Any()) {
       Context.Database.Migrate();
    }
    
    // or async as in your code...
    if (!Context.Users.Any()) {
       ...
    }
    

    As a final note, if you are not using migrations, you may want to use EnsureCreated, instead.