0

I need to create users and roles at the first startup of my web application. For that, I write my code into the Configure() function in Startup.cs.

When I run my application, I get this error:

An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code at the call of my first function "CreateUsers"

Code:

 public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
{
   ...
        await CreateUsers(context, serviceProvider);
        await CreateRoles(context, serviceProvider);
    }

    private async Task CreateUsers(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        List<ApplicationUser> users = new List<ApplicationUser>();
        users.Add(new ApplicationUser { UserName = "devUser", Email = "dev@dev.com", LastName = "dev", FirstName = "dev", PasswordHash = "devpassword" });
        users.Add(new ApplicationUser { UserName = "workUser", Email = "work@work.com", LastName = "work", FirstName = "work", PasswordHash = "workPassword" });

        foreach(var user in users)
        {
            var userExist = await _userManager.FindByEmailAsync(user.Email);
            if(userExist != null)
            {
                await _userManager.CreateAsync(user, user.PasswordHash);
                context.Users.Add(user);
                context.SaveChanges();
            }
        }
    }

    private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        List<IdentityRole> roles = new List<IdentityRole>();
        roles.Add(new IdentityRole { Name = "Developer", NormalizedName = "DEVELOPER" });
        roles.Add(new IdentityRole { Name = "Work", NormalizedName = "WORK" });
        roles.Add(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" });
        roles.Add(new IdentityRole { Name = "Redacteur", NormalizedName = "REDACTEUR" });
        roles.Add(new IdentityRole { Name = "Correcteur", NormalizedName = "CORRECTEUR" });
        roles.Add(new IdentityRole { Name = "Membre", NormalizedName = "MEMBRE" });

        foreach(var role in roles)
        {
            var roleExist = await RoleManager.RoleExistsAsync(role.Name);
            if(!roleExist)
            {
                context.Roles.Add(role);
                context.SaveChanges();
            }
        }

        var devuser = await UserManager.FindByEmailAsync("dev@dev.com");
        await UserManager.AddToRoleAsync(devuser, "DEVELOPER");
        var work = await UserManager.FindByEmailAsync("work@work.com");
        await UserManager.AddToRoleAsync(work, "WORK");
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Y.Berthoud
  • 75
  • 8
  • 1
    Check the `InnerException` property in your `AggregateException` and see the actual exception raised – Jcl Feb 08 '16 at 11:46
  • {"Object reference not set to an instance of an object."} ? that ? – Y.Berthoud Feb 08 '16 at 11:48
  • Yes, that's your actual exception: which line does throw the exception? – Jcl Feb 08 '16 at 11:49
  • Maybe not relevant to your question but you probably should do it in the seed method of the Configuration class in the database migration? – Gang Gao Feb 08 '16 at 11:50
  • "seed" method doesn't exist int mvc6 :) @Jcl: just on my first look into the foreach, he takes "var userExist = await UserManager.FindByEmailAsync(user.Email);" and after that i throw the exception. this method verify with this code: public class ApplicationDbContext : IdentityDbContext { protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } – Y.Berthoud Feb 08 '16 at 11:55
  • @Y.Berthoud `_userManager` is not null, is it? Have you made a line-by-line debugging and checked it? – Jcl Feb 08 '16 at 11:56
  • @Jcl: yep, look my previous answer. The error was send because "OnModelCreating" return null. Well. I think i need to override this or create ApplicationUserDbContext. – Y.Berthoud Feb 08 '16 at 11:58
  • `OnModelCreating` doesn't return anything, it's a `void` function. I'm not sure I'm following you – Jcl Feb 08 '16 at 11:59
  • Yeah, excuse my english :) var userExist = await UserManager.FindByEmailAsync(user.Email); This method passes into OnModelCreating. then take the null value and returns me the error. – Y.Berthoud Feb 08 '16 at 12:01
  • I'm sorry but I still don't follow. The error is that you are somehow trying to access an object (usually a property or function of that object) which is `null`. Check [this question](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) for suggestions on how to find and debug your code to find that `null` value. There's not a lot we can do from here. – Jcl Feb 08 '16 at 12:16
  • the "await" return me the error. If i remove them it is work – Y.Berthoud Feb 08 '16 at 12:43

0 Answers0