Entity framework Core with Identity and ASP.NET Core RC2 not creating user in database

♀尐吖头ヾ 提交于 2019-12-24 09:40:04

问题


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

  • ASP.NET Core RC2
  • Entity Framework Core
  • The Npgsql EFCore driver

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.

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.

Here is my DataSeeder class:

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"));
        }
    }
}

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


回答1:


Check the result of _userManager.createAsync.

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

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

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



来源:https://stackoverflow.com/questions/38053948/entity-framework-core-with-identity-and-asp-net-core-rc2-not-creating-user-in-da

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!