具有Identity和ASP.NET Core RC2的实体框架Core无法在数据库中创建用户 [英] Entity framework Core with Identity and ASP.NET Core RC2 not creating user in database

查看:55
本文介绍了具有Identity和ASP.NET Core RC2的实体框架Core无法在数据库中创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理带有身份验证的应用程序。我正在使用以下框架:

I am working on an application with authentication. I am using the following frameworks:


  • ASP.NET Core RC2

  • 实体框架核心

  • Npgsql EFCore驱动程序

对于种子,我创建了 DataSeeder 类,该类作为临时服务添加到 ConfigureServices 函数中,随后在Configure函数中调用。它会检查 IdentityUser 是否存在,如果不存在,则会创建一个名为admin的角色,并将角色Admin添加到其中。

For seeding I created a DataSeeder class, that gets added as Transient Service in the ConfigureServices function and later called in the Configure function. It checks whether an IdentityUser exists, and if not it creates one called admin and adds the role Admin to it.

但是,当向用户添加角色时,出现一个异常,表明违反了外键约束,并且ASP_NET_USERS不包含具有该PK的条目。

However, when adding the role to the user, I get an exception saying that a foreign key constraint gets violated and that the ASP_NET_USERS does not contain an entry with that PK.

我检查了数据库,它确实包含我创建的新角色,但是用户表仍然为空。

I checked the database and it does indeed contain the new Role that I created, but the user table is still empty.

这是我的 DataSeeder 类:

public class DataSeeder {
    private DatabaseContext _context;
    private UserManager<IdentityUser> _userManager;
    private RoleManager<IdentityRole> _roleManager;

    public DataSeeder(DatabaseContext ctx, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager) {
        _context = ctx;
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public async Task CreateUserAsync() {
        if (! await _userManager.Users.AnyAsync()) {
            var adminRole = new IdentityRole("admin");
            var rootRole = new IdentityRole("root");

            await _roleManager.CreateAsync(adminRole);
            await _roleManager.CreateAsync(rootRole);

            var user = new IdentityUser {
                Email = "blabla@example.com",
                EmailConfirmed = true,
                UserName = "superadmin"
            };

            await _userManager.CreateAsync(user, "P@SSWORD");

            await _userManager.AddClaimAsync(user, new Claim("role", "admin"));
        }
    }
}

因此在 AddClaimAsync 。任何帮助将不胜感激

So the exception is thrown at AddClaimAsync. Any help would be really appreciated

推荐答案

检查 _userManager.createAsync 。

var result = await _userManager.CreateAsync(user, "P@SSWORD");

if (!result.Succeeded)
{
    // something went wrong, inspect the errors
}

您很可能会在 IdentityUser 上找到必需的属性,或者密码无效

You'll most likely find a required property on your IdentityUser is missing or the password is not valid.

这篇关于具有Identity和ASP.NET Core RC2的实体框架Core无法在数据库中创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆