Entity framework 将数据种子添加到UserRole表.net核心

Entity framework 将数据种子添加到UserRole表.net核心,entity-framework,asp.net-core-mvc,user-roles,Entity Framework,Asp.net Core Mvc,User Roles,在启动.NET核心默认MVC应用程序上的项目之前,我希望使用管理员用户为默认数据库添加种子。代码如下: public void SeedDb(ApplicationDbContext Context, IServiceProvider ServiceProvider, IConfiguration Configuration) { if (Context.Users.Count() > 0) return; var UserManager = S

在启动.NET核心默认MVC应用程序上的项目之前,我希望使用管理员用户为默认数据库添加种子。代码如下:

public void SeedDb(ApplicationDbContext Context, IServiceProvider ServiceProvider, IConfiguration Configuration)
    {

        if (Context.Users.Count() > 0) return;

        var UserManager = ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();

        var ApplicationUser = new ApplicationUser()
        {
            Email = Configuration["Email"],
            NormalizedEmail = Configuration["Email"],
            LockoutEnabled = false,
            NormalizedUserName = Configuration["Email"],
            SecurityStamp = "579355dd - a64c - 498d - a0b5 - 9e55754c9109",
            EmailConfirmed = true,
            ConcurrencyStamp = null,
            Id = "977ec1a5-1ae7-4658-952a-6b5dccd75a85",
            PasswordHash ="",
            PhoneNumber = "333333333333",
            LockoutEnd = null,
            AccessFailedCount = 1,
            PhoneNumberConfirmed = true,
            TwoFactorEnabled = false,
            UserName = Configuration["Email"]
        };

        var Password =  HashPassword(ApplicationUser, Configuration["Password"]);

        if (VerifyHashedPassword(ApplicationUser, Password, Configuration["Password"]) == PasswordVerificationResult.Success)
        {
            ApplicationUser.PasswordHash = Password;
        }

        Context.Users.Add(ApplicationUser);
        Context.SaveChanges();

        var RoleManager = ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        string[] Roles = { "Admin", "Manager", "User" };

        foreach (string RoleName in Roles) {
            RoleManager.CreateAsync(new IdentityRole(RoleName));
        }

         var Admin = Context.Users.SingleOrDefault(m => m.Email == Configuration["Email"]);
         var Role =  Context.Roles.SingleOrDefault(m => m.Name == Configuration["Role"]);
         IdentityUserRole<string> UserRole = new IdentityUserRole<string>() { UserId = Admin.Id, RoleId = Role.Id };

         Context.UserRoles.Add(UserRole);
         Context.SaveChanges();
    }
public void SeedDb(ApplicationDbContext上下文、iSeries Provider服务提供程序、IConfiguration配置)
{
if(Context.Users.Count()>0)返回;
var UserManager=ServiceProvider.GetRequiredService();
var ApplicationUser=new ApplicationUser()
{
电子邮件=配置[“电子邮件”],
NormalizedEmail=配置[“电子邮件”],
LockoutEnabled=false,
NormalizedUserName=配置[“电子邮件”],
SecurityStamp=“579355dd-a64c-498d-a0b5-9e55754c9109”,
emailconfirm=true,
ConcurrencyStamp=null,
Id=“977ec1a5-1ae7-4658-952a-6b5dccd75a85”,
PasswordHash=“”,
PhoneNumber=“333”,
LockoutEnd=null,
AccessFailedCount=1,
PhoneNumber确认=真,
TwoFactorEnabled=false,
用户名=配置[“电子邮件”]
};
var Password=HashPassword(应用程序用户,配置[“密码]);
if(VerifyHashedPassword(应用程序用户、密码、配置[“密码])==PasswordVerificationResult.Success)
{
ApplicationUser.PasswordHash=密码;
}
Context.Users.Add(ApplicationUser);
SaveChanges();
var rolemager=ServiceProvider.GetRequiredService();
字符串[]角色={“管理员”、“经理”、“用户”};
foreach(角色中的字符串RoleName){
CreateAsync(新的IdentityRole(RoleName));
}
var Admin=Context.Users.SingleOrDefault(m=>m.Email==Configuration[“Email”]);
var Role=Context.Roles.SingleOrDefault(m=>m.Name==Configuration[“Role”]);
IdentityUserRole UserRole=newidentityUserRole(){UserId=Admin.Id,RoleId=Role.Id};
Context.UserRoles.Add(UserRole);
SaveChanges();
}

除了我不能在UserRole数据库中植入数据外,一切都运行得很好。我从DBContext添加IdentityUserRole实体并将更改保存到DB。虽然没有通过DB。有什么建议吗?

创建一个名为
startupbinitializer
的类:

using System;
using System.Collections.Generic;
using System.Linq;
using Core.Entities;
using Microsoft.AspNetCore.Identity;

namespace Core.Startups
{
    public class StartupDbInitializer
    {
        private const string AdminEmail = "admin@admin.com";
        private const string AdminPassword = "StrongPasswordAdmin123!";

        private static readonly List<IdentityRole> Roles = new List<IdentityRole>()  
        {
            new IdentityRole {Name = "Admin", NormalizedName = "ADMIN", ConcurrencyStamp = Guid.NewGuid().ToString()}
        };

        public static void SeedData(ApplicationDbContext dbContext, UserManager<User> userManager)
        {
            dbContext.Database.EnsureCreated();
            AddRoles(dbContext);
            AddUser(dbContext, userManager);
            AddUserRoles(dbContext, userManager);
        }

        private static void AddRoles(ApplicationDbContext dbContext)
        {
            if (!dbContext.Roles.Any())
            {
                foreach (var role in Roles)
                {
                    dbContext.Roles.Add(role);
                    dbContext.SaveChanges();
                } 
            }
        }

        private static async void AddUser(ApplicationDbContext dbContext, UserManager<User> userManager)
        {
            if (!dbContext.Users.Any())
            {
                var user = new User { 
                    UserName = AdminEmail, 
                    Email = AdminEmail, 
                    IsEnabled = true, 
                    EmailConfirmed = true,
                };
                await userManager.CreateAsync(user, AdminPassword);
            }
        }

        private static void AddUserRoles(ApplicationDbContext dbContext, UserManager<User> userManager)
        {
            if (!dbContext.UserRoles.Any())
            {
                var userRole = new IdentityUserRole<string>
                {
                    UserId = dbContext.Users.Single(r => r.Email == AdminEmail).Id,
                    RoleId = dbContext.Roles.Single(r => r.Name == "Admin").Id
                };
                dbContext.UserRoles.Add(userRole);
                dbContext.SaveChanges();
            }
        }
    }
}

在上面,我插入了我的
DbContext
UserManager

试试这一行。。。它必须起作用

ApplicationUser user = await _usermanager.FindByEmailAsync("your.email@mymail.com");
if (!await _usermanager.IsInRoleAsync(user, "Admin"))
{
    await _usermanager.AddToRoleAsync(user, "Admin");
}
当您尝试了它,它的工作,改变它为您的配置参数,如果您喜欢他们。要让它工作起来并不难,在UserManager和RoleManager类中,您拥有所需的一切

我还是说,在插入表之前,您必须检查表中是否存在该角色。在添加检查之前,每次运行应用程序时,我都会填充所有角色

if ((await _roleManager.FindByNameAsync("Admin")) == null)
{
    await _roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
}

尝试UserManager.AddToRoleAsync(用户,角色)在创建角色之前,您还应该检查角色是否不存在,否则每次启动应用程序时都会创建角色。我尝试了UserManager.AddToRole(用户,角色),但没有发生任何事情,db下没有通过。AddtoRole文档还说,它不会将数据持久化到Store,所以我们要说的是,您必须在C#中编写创建此数据的脚本,并一次性运行它?
if ((await _roleManager.FindByNameAsync("Admin")) == null)
{
    await _roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
}