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 read from 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);
}
}
}
}