Asp.net core Identity "The INSERT statement conflicted with the FOREIGN KEY constraint "

12.8k views Asked by At

I create ASP.NET CORE application with ASP.NET CORE Identity. I create seed class for saving new users and roles for first startup application. Inside this seed class I get following error when I add Role To User.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "DB_A14695_Elvinm", table "dbo.AspNetUsers", column 'Id'. The statement has been terminated.

I used following class for Identity

public class ApplicationUser : IdentityUser
{
    public int Type { get; set; }
    public int Flags { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime LastModifiedDate { get; set; }
}

And my seed class

 public class DbSeeder
{
    #region Private Members
    private RvMusicalDbContext DbContext;
    private RoleManager<IdentityRole> RoleManager;
    private UserManager<ApplicationUser> UserManager;
    #endregion Private Members

    #region Constructor
    public DbSeeder(RvMusicalDbContext dbContext, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        DbContext = dbContext;
        RoleManager = roleManager;
        UserManager = userManager;
    }
    #endregion Constructor

    #region Public Methods
    public async Task SeedAsync()
    {
        // Create the Db if it doesn’t exist
        DbContext.Database.EnsureCreated();
        // Create default Users
        if (await DbContext.Users.CountAsync() == 0) await CreateUsersAsync();
    }
    #endregion Public Methods

    #region Seed Methods
    private async Task CreateUsersAsync()
    {
        // local variables
        DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00);
        DateTime lastModifiedDate = DateTime.Now;
        string role_Administrators = "Administrators";
        string role_Registered = "Registered";

        //Create Roles (if they doesn't exist yet)
        if (!await RoleManager.RoleExistsAsync(role_Administrators)) await RoleManager.CreateAsync(new IdentityRole(role_Administrators));
        if (!await RoleManager.RoleExistsAsync(role_Registered)) await RoleManager.CreateAsync(new IdentityRole(role_Registered));

        // Create the "Admin" ApplicationUser account (if it doesn't exist already)
        var user_Admin = new ApplicationUser()
        {
            UserName = "Admin",
            Email = "[email protected]",
            CreatedDate = createdDate,
            LastModifiedDate = lastModifiedDate,
            Flags = 0,
            Type = 0
        };

        // Insert "Admin" into the Database and also assign the "Administrator" role to him.
        if (await UserManager.FindByIdAsync(user_Admin.Id) == null)
        {
            await UserManager.CreateAsync(user_Admin, "Pass4Admin");
            /// ERROR OCCURED HERE
            await UserManager.AddToRoleAsync(user_Admin, role_Administrators);
            // Remove Lockout and E-Mail confirmation.
            user_Admin.EmailConfirmed = true;
            user_Admin.LockoutEnabled = false;
        }

    #endregion Seed Methods


}

I want to say that roles saved database successfully.

Please help to solve problem.

5

There are 5 answers

7
Dave On BEST ANSWER

Check the output of UserManager.CreateAsync call right before the error. I'm guessing your user doesn't get persisted so the next call fails with an FK issue.

If you are using the default identity password requirements (like I was when I tried it) you get a password validation error result from the user creation call.

enter image description here

2
KevDevMan On

Should you be ensuring the user admin has an ID

if (await UserManager.FindByIdAsync(user_Admin.Id) == null)

should be

if (await UserManager.FindByIdAsync(user_Admin.Id) != null)
0
Ryan On

I know this was answered but I just had to add my solution to my problem in the hopes that I can save some other poor soul from repeating my mistake.....

My user WAS created...

I just wasn't clicking the 'refresh' button on the SQL Server Object Explorer.

:( How embarrassing. I spent an hour+ tracking this down.

Edit: I see I got a negative vote. I had the same problem that the individual asking the question had and my solution was that the page needed refreshed. Although it was a stupid mistake, it's usually safe to assume that when you make a mistake, you are not the only one. My answer is a correct answer in all cases where the user didn't refresh the page, which I believe makes it a decent answer.

0
Visratha On

I ran into the same issue and none of answers here worked, eventually I found solution to that. When you have custom User table verify that in your recently created migration references that point to table AspNetUsers instead point to your custom ApplicationUser table. If not, drop database, manually modify migration file and apply changes.

0
ggedikli On

I had the same problem. That was the solution; go to DBContext and remove the user in the inherited class.

Before:

public class MyDBContext : IdentityDbContext<MyUser>
{ }

After:

public class MyDBContext : IdentityDbContext
{ }