数据库中的 MVC5 身份种子用户

MVC5 Identity Seed Users in database

我收到一条错误消息:"UserId not found." 尝试将多个用户植入我的数据库时。

这是我的种子方法:

protected override void Seed(newBestPlay.Models.ApplicationDbContext context)
{
    //  This method will be called after migrating to the latest version.
    InitialCreate create = new InitialCreate();
    create.Down();
    create.Up();
    context.Configuration.LazyLoadingEnabled = true;

    if (!context.Roles.Any(r => r.Name == "Admin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "Admin" };
        manager.Create(role);
    }

    if (!context.Roles.Any(r => r.Name == "User"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "User" };
        manager.Create(role);
    }

    if (!context.Users.Any(u => u.UserName == "user1"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "user1", Email = "email1" };
        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "Admin");
    }

    if (!context.Users.Any(u => u.UserName == "user2"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "user2", Email = "email2" };
        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "Admin");
    }
}

最后 "manager.AddToRole" 行失败。我发现第二个用户甚至没有被添加到数据库中,所以它找不到 user.Id 因为它从未被添加过。

想通了。它不允许在我的用户名中使用破折号。我的用户名(电子邮件)在域部分有破折号。我必须添加

this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };

将我的 IdentityConfig.cs 文件放入 ApplicationUserManager 构造函数中,现在它看起来像这样:

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
            this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
        }
.....

将此添加到您的种子方法中:

var manager = new UserManager<ApplicationUser>(store);

  manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,

            };