嘿这可能是一个新手问题,但老实说,经过几个小时寻找答案后,我找不到问题。
我正在尝试通过播种数据库来创建两个角色和一个管理员用户。我没有编译错误,但在运行应用程序后我无法登录,所以我检查了数据库并注意到角色创建成功但不是管理员用户。
以下是我用于播种的课程:
public class Initialize
{
public static async Task InitializeAsync(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService < RoleManager<IdentityRole>>();
UserManager<ApplicationUser> userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] rolenames = { "Admin","Member"};
IdentityResult roleResult;
foreach (var roleName in rolenames) {
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
string username = "admin";
string email = "admin@example.com";
string password = "Secret123";
string role = "Admin";
if (await userManager.FindByEmailAsync(username) == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = username,
Email = email
};
IdentityResult result = await userManager
.CreateAsync(user, password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, role);
}
}
}
}
我的ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
这是我的Program.cs:
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
Initialize.InitializeAsync(context, services).Wait();
}
catch(Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Error seeding");
}
}
host.Run();
}
感谢任何帮助:)
答案 0 :(得分:0)
在通过 serviceProvider.GetRequiredService 访问后,尝试查看 userManager->存储->用户->结果视图->消息。您可以在此处找到一些错误消息。
如果它包含一条消息:
“无法为'ApplicationUser'创建DbSet,因为此类型不是 包含在上下文模型中。”
您必须更改从 IdentityDbContext 继承的 ApplicationContext 类,它应该可以正常工作。