我正在尝试使用数据在.net核心中播放数据库。 首先,我正确地为管理员用户提供用户,用户角色和角色。 由于项目的要求,我做了两个模型讲师,学生 我也用另一个脚本播种这些表格。 我希望每位教师和学生都能看到用户表(Iwant单独表格授权) 我编写以下脚本在program.cs文件中最后运行
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication.Models;
namespace WebApplication.Data
{
public static class AssingUsers
{
public static void Initialize(IConfiguration Configuration, ApplicationDbContext context, UserManager<ApplicationUser> UserManage)
{
AddUser(Configuration, context, UserManage);
AddUserRoles(Configuration, context, UserManage);
}
private static async void AddUser(IConfiguration Configuration, ApplicationDbContext DBContext, UserManager<ApplicationUser> UserManager)
{
if (DBContext.Instructors.Any())
{
foreach (Instructor instructor in DBContext.Instructors)
{
var User = new ApplicationUser
{
UserName = instructor.Email,
Email = instructor.Email,
EmailConfirmed = true
};
await UserManager.CreateAsync(User, Configuration["Password"]);
}
}
if (DBContext.Students.Any())
{
foreach (Student student in DBContext.Students)
{
var User = new ApplicationUser
{
UserName = student.Email,
Email = student.Email,
EmailConfirmed = true
};
await UserManager.CreateAsync(User, Configuration["Password"]);
}
}
}
private static void AddUserRoles(IConfiguration Configuration, ApplicationDbContext DBContext, UserManager<ApplicationUser> UserManager)
{
if (DBContext.Students.Any())
{
foreach (Student st in DBContext.Students)
{
var UserRole = new IdentityUserRole<string>
{
UserId = DBContext.Users.Single(r => r.Email == st.Email).Id,
RoleId = DBContext.Roles.Single(r => r.Name == "User").Id
};
DBContext.UserRoles.Add(UserRole);
}
DBContext.SaveChanges();
}
if (DBContext.Instructors.Any())
{
foreach (Instructor ins in DBContext.Instructors)
{
var UserRole = new IdentityUserRole<string>
{
UserId = DBContext.Users.Single(x => x.Email == ins.Email).Id,
RoleId = DBContext.Roles.Single(x => x.Name == "Manager").Id
};
DBContext.UserRoles.Add(UserRole);
}
DBContext.SaveChanges();
}
}
}
}
虽然一切都很完美,但我在教师和学生桌上播种时遇到了问题。 我尝试通过_context.Users.Add()进行同步,但同样没有。 有什么建议吗?