【问题标题】:Seed identity user table with changed id column?更改 id 列的种子身份用户表?
【发布时间】:2016-03-19 07:24:37
【问题描述】:

我已将 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?

【问题讨论】:

    标签: asp.net-mvc-5 asp.net-identity usermanager


    【解决方案1】:

    实际上,当您保存用户时,它还没有给出 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();
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 1970-01-01
      • 2011-01-09
      • 2019-09-19
      • 2014-10-23
      • 1970-01-01
      • 2017-02-02
      • 2015-07-31
      • 2017-11-10
      相关资源
      最近更新 更多