0

次のコードを使用して、AspNetUser (ID) タブをユーザーのみに変更しました。

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

「UserId が見つかりません」というエラー メッセージが表示されます。私の UserManager.Create が失敗したようです。

標準 ID の代わりに UserID を使用するようにシード コードを変更するにはどうすればよいですか?

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 に答える