Rate my Seed class

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
28,053
Reaction score
17,806
Hey guys. I would appreciate a small small code review please. Busy wrapping up this project now. Does everything check out(pun not intended) with this?

C#:
public static class SeedUsersAndData
{
    //seed data lol
    public static void SeedData(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IServiceProvider serviceProvider)
    {
        var context = serviceProvider.GetService<EMSDBContext>();

        if (!context.UserTypes.Any())
        {
            context.UserTypes.AddRange(
                new UserType { Description = "Permanent", RemunerationRate = 12.50M },
                new UserType { Description = "Temp", RemunerationRate = 12.65M },
                new UserType { Description = "Contractor", RemunerationRate = 8.00M });

            context.SaveChanges();
        }

        if (!context.JobTypes.Any())
        {
            context.JobTypes.AddRange(
                new JobType { Description = "Clean Windows", Duration = 12.50M },
                new JobType { Description = "Paint Bollards", Duration = 12.65M },
                new JobType { Description = "Service Printers", Duration = 8.00M },
                new JobType { Description = "Stock Taking", Duration = 2.45M });

            context.SaveChanges();
        }

        if (!context.Jobs.Any())
        {
            context.Jobs.AddRange(
                new Job { JobNo = "CC55", JobTypeId = 1, StartDate = Convert.ToDateTime("2021-07-25"), EndDate = Convert.ToDateTime("2021-07-28") },
                new Job { JobNo = "GT0001", JobTypeId = 2, StartDate = Convert.ToDateTime("2021-08-01"), EndDate = Convert.ToDateTime("2021-08-10") });

            context.SaveChanges();
        }

        //seed user role
        if (!roleManager.RoleExistsAsync("User").Result)
        {
            IdentityRole role = new IdentityRole
            {
                Name = "User"
            };

            var roleResult = roleManager.CreateAsync(role).Result;
        }

        //seed administrator role
        if (!roleManager.RoleExistsAsync("Administrator").Result)
        {
            IdentityRole role = new IdentityRole
            {
                Name = "Administrator"
            };

            var roleResult = roleManager.CreateAsync(role).Result;
        }

        //create administrator
        if (userManager.FindByEmailAsync("[email protected]").Result == null)
        {
            var appAdmin = new ApplicationUser
            {
                Email = "[email protected]",
                NormalizedEmail = "[email protected]",
                EmailConfirmed = true,
                UserName = "[email protected]",
                NormalizedUserName = "[email protected]",
                UserTypeId = 1,
                RemunerationRate = 1.0M
            };

            var result = userManager.CreateAsync(appAdmin, "Qazasdwsx12!").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(appAdmin, "Administrator").Wait();
            }
        }

        //create user
        if (userManager.FindByEmailAsync("[email protected]").Result == null)
        {
            var appUser = new ApplicationUser
            {
                Email = "[email protected]",
                NormalizedEmail = "[email protected]",
                EmailConfirmed = true,
                UserName = "[email protected]",
                NormalizedUserName = "[email protected]",
                UserTypeId = 2,
                RemunerationRate = 1.0M
            };

            var result = userManager.CreateAsync(appUser, "Qazasdwsx12!").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(appUser, "User").Wait();
            }
        }
    }
}

C#:
public static async Task Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var serviceScope = host.Services.CreateScope())
    {
        var services = serviceScope.ServiceProvider;
        var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();

        try
        {
            //apply migration and seed data
            var dbContext = serviceScope.ServiceProvider.GetRequiredService<EMSDBContext>();
            serviceScope.ServiceProvider.GetRequiredService<ILoggerFactory>();
            await dbContext.Database.MigrateAsync();

            SeedUsersAndData.SeedData(userManager, roleManager, services);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred seeding the DB.");
        }
    }

    await host.RunAsync();
}
 
Last edited:
Seems fine

use “async/await” instead of “.Result”. It is non blocking and is the preferred way do do this.

one of the advantages of using “.HasData” instead of what is done here, is that the seed data will become part of your migrations. So if you change the seed data, you will get a new migration. Obviously you need to be using migrations though
 
Seems fine

use “async/await” instead of “.Result”. It is non blocking and is the preferred way do do this.

one of the advantages of using “.HasData” instead of what is done here, is that the seed data will become part of your migrations. So if you change the seed data, you will get a new migration. Obviously you need to be using migrations though

Great thanks kabal.

I did try to use async/await and ran into an issue. Not seen this one before. I will tinker with this class for a bit and see if I can come right.

Seed-Error.jpg


 
Last edited:
Top
Sign up to the MyBroadband newsletter
X