0

I have changed the AspNetUser (identity) tabe to only user with the following code.

        // Change the name of the table to be Users instead of AspNetUsers
        modelBuilder.Entity<IdentityUser>()
            .ToTable("Users").Property(p => p.Id).HasColumnName("UserID");
        modelBuilder.Entity<ApplicationUser>()
            .ToTable("Users").Property(p => p.Id).HasColumnName("UserID");

My application works fine but not my seed. I have this code in Migrations/Configuration.cs

        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        string role = "Admin";
        string password = "Password@1234";

        //Create Role Admin if it does not exist
        if (!RoleManager.RoleExists(role))
        {
            var roleresult = RoleManager.Create(new IdentityRole(role));
        }

        //Create Admin users with password=123456
        var admin1 = new ApplicationUser();
        admin1.UserName = "admin1@admin1.com";
        admin1.Email = "admin1@admin1.com";
        admin1.EmailConfirmed = true;
        UserManager.Create(admin1, password);
        UserManager.AddToRole(admin1.Id, role);

        context.SaveChanges();

I get the error message "UserId not found". Seems like my UserManager.Create fails.

How can I change my seed code to use the UserID insted of standard Id?

Anders
  • 375
  • 2
  • 5
  • 18

1 Answers1

0

Actually, when you save the user, it does not have an id given yet, you'll have to retrieve the user in between the creation of the user & addToRole:

    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    string role = "Admin";
    string password = "Password@1234";

    //Create Role Admin if it does not exist
    if (!RoleManager.RoleExists(role))
    {
        var roleresult = RoleManager.Create(new IdentityRole(role));
    }

    //Create Admin users with password=123456
    var admin1 = new ApplicationUser();
    admin1.UserName = "admin1@admin1.com";
    admin1.Email = "admin1@admin1.com";
    admin1.EmailConfirmed = true;
    UserManager.Create(admin1, password);

    // Refetch user with ID:
    dbAdmin1 = context.Users.FirstOrDefault(x => x.UserName == admin1.UserName);

    UserManager.AddToRole(dbAdmin1.Id, role);

    context.SaveChanges();
Jelle Oosterbosch
  • 1,731
  • 15
  • 17