【问题标题】:How can I add admin user using OnModelCreating in ASP.NET Identity?如何在 ASP.NET Identity 中使用 OnModelCreating 添加管理员用户?
【发布时间】:2019-12-15 07:57:14
【问题描述】:

如何在 ASP.NET Identity 中使用 OnModelCreating 添加管理员用户?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<IdentityUser>
    (
       user.UserName = "admin";
       user.Email = "admin@gmail.com";
       string userPassword = "Admin123#";
    ).ToTable("AspNetUsers");
}

【问题讨论】:

  • 您必须提供所有必填字段

标签: c# entity-framework asp.net-core


【解决方案1】:

试试这个:

 protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // any unique string id
        const string ADMIN_ID = "a18be9c0-aa65-4af8-bd17-00bd9344e575";
        const string ROLE_ID = "ad376a8f-9eab-4bb9-9fca-30b01540f445";

        builder.Entity<IdentityRole>().HasData(new IdentityRole
        {
            Id = ROLE_ID,
            Name = "admin",
            NormalizedName = "admin"
        });

        var hasher = new PasswordHasher<IdentityUser>();
        builder.Entity<IdentityUser>().HasData(new IdentityUser
        {
            Id = ADMIN_ID,
            UserName = "admin",
            NormalizedUserName = "admin",
            Email = "admin@gmail.com",
            NormalizedEmail = "admin@gmail.com",
            EmailConfirmed = false,
            PasswordHash = hasher.HashPassword(null, "Admin123#"),
            SecurityStamp = string.Empty
        });

        builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
        {
            RoleId = ROLE_ID,
            UserId = ADMIN_ID
        });
    }

参考:

https://inneka.com/programming/c/how-to-seed-an-admin-user-in-ef-core-2-1-0/

【讨论】:

    【解决方案2】:

    如何在 ASP.NET Identity 中使用 OnModelCreating 添加管理员用户?

    这种方法你不要这样做

    OnModelCreating 的文档说明:

    通常,此方法仅在派生上下文的第一个实例创建时调用一次。

    这适用于创建 Context 时,而不是创建上下文中任何已定义的类型化 dbset 时。

    如果您想在将对象发送到数据库之前对其进行更改,则有其他帖子可以回答。

    How to create new entity object, modify it in Model before SaveChanges()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多