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

asp.net-core entity-framework-core

Question

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
1
6/27/2016 12:37:46 PM

Accepted Answer

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.

1
6/28/2016 1:03:41 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow