How to seed an Admin user in EF Core 2.1.0?

后端 未结 6 1405
感情败类
感情败类 2020-11-29 02:40

I have an ASP.NET Core 2.1.0 application using EF Core 2.1.0.

How do I go about seeding the database with Admin user and give him/her an Admin role? I cannot find an

6条回答
  •  离开以前
    2020-11-29 03:24

    Actually a User Entity can be seeded in OnModelCreating, one thing to consider: the IDs should be predefined. If type string is used for TKey identity entities, then there is no problem at all.

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // any guid
        const string ADMIN_ID = "a18be9c0-aa65-4af8-bd17-00bd9344e575";
        // any guid, but nothing is against to use the same one
        const string ROLE_ID = ADMIN_ID;
        builder.Entity().HasData(new IdentityRole
        {
            Id = ROLE_ID,
            Name = "admin",
            NormalizedName = "admin"
        });
    
        var hasher = new PasswordHasher();
        builder.Entity().HasData(new UserEntity
        {
            Id = ADMIN_ID,
            UserName = "admin",
            NormalizedUserName = "admin",
            Email = "some-admin-email@nonce.fake",
            NormalizedEmail = "some-admin-email@nonce.fake",
            EmailConfirmed = true,
            PasswordHash = hasher.HashPassword(null, "SOME_ADMIN_PLAIN_PASSWORD"),
            SecurityStamp = string.Empty
        });
    
        builder.Entity>().HasData(new IdentityUserRole
        {
            RoleId = ROLE_ID,
            UserId = ADMIN_ID
        });
    }
    

提交回复
热议问题