0

我已将 AspNetUser(身份)标签更改为仅具有以下代码的用户。

        // 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");

我的应用程序运行良好,但不是我的种子。我在 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();

我收到错误消息“找不到用户 ID”。好像我的 UserManager.Create 失败了。

如何更改我的种子代码以使用标准 ID 的用户 ID?

4

1 回答 1

0

实际上,当您保存用户时,它还没有给出 id,您必须在创建用户和 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();
于 2015-12-14T09:11:35.620 回答