加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 如何在EF Core 2.1.0中为Admin用户播种?

发布时间:2020-12-16 04:02:06 所属栏目:asp.Net 来源:网络整理
导读:我有一个使用EF Core 2.1.0的ASP.NET Core 2.1.0应用程序. 如何使用Admin用户为数据库播种并为其授予管理员角色?我找不到任何关于此的文件. 解决方法 因为用户不能以正常方式在Identity中播种,就像其他表使用.NET Core 2.1的.HasData()播种一样. .NET Core
我有一个使用EF Core 2.1.0的ASP.NET Core 2.1.0应用程序.

如何使用Admin用户为数据库播种并为其授予管理员角色?我找不到任何关于此的文件.

解决方法

因为用户不能以正常方式在Identity中播种,就像其他表使用.NET Core 2.1的.HasData()播种一样.

.NET Core 2.1中的种子角色使用ApplicationDbContext类中给出的代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example,you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin",NormalizedName = "Admin".ToUpper() });
    }

具有角色的种子用户按照以下步骤操作.

第1步:创建新类

public static class ApplicationDbInitializer
{
    public static void SeedUsers(UserManager<IdentityUser> userManager)
    {
        if (userManager.FindByEmailAsync("abc@xyz.com").Result==null)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = "abc@xyz.com",Email = "abc@xyz.com"
            };

            IdentityResult result = userManager.CreateAsync(user,"PasswordHere").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user,"Admin").Wait();
            }
        }       
    }   
}

步骤2:现在修改Startup.cs类中的ConfigureServices方法.

修改前:

services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

修改后:

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

步骤3:修改Startup.cs类中Configure Method的参数.

修改前:

public void Configure(IApplicationBuilder app,IHostingEnvironment env)
    {
        //..........
    }

修改后:

public void Configure(IApplicationBuilder app,IHostingEnvironment env,UserManager<IdentityUser> userManager)
    {
        //..........
    }

第4步:调用Seed(ApplicationDbInitializer)类的方法:

ApplicationDbInitializer.SeedUsers(userManager);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读