Home > Enterprise >  The INSERT statement conflicted with the FOREIGN KEY using EF Core
The INSERT statement conflicted with the FOREIGN KEY using EF Core

Time:06-23

I'm trying to generate id using Microsoft.AspNetCore.Identity for fill userData.AspNetUserID property and I got this error message in my console:

System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "JET", table "dbo.AspNetUsers", column 'Id'.

Can anyone help fix this error?

This is my code:

    public async Task<IActionResult> CopyUserRole(int id)
    { 
        var result  = _context.UserData.Where(m => m.UserDataID == id).FirstOrDefault();
        var userData = new UserData();
        var email = result.Email.Insert(0, "copy-");

        var user = new ApplicationUser { UserName = email, Email = email };
        var UserManager = await _userManager.CreateAsync(user, "12345678");

        if(!await _roleManager.RoleExistsAsync(result.Role))
        {
            await _roleManager.CreateAsync(new IdentityRole(result.Role));
        }

        var success = await _userManager.AddToRoleAsync(user, result.Role);

        //userData.UserDataID     = 0;
        userData.AspNetUserID   = user.Id;
        userData.DeviceID       = result.DeviceID;
        userData.PhotoUrl       = result.PhotoUrl;
        userData.Status         = result.Status;
        userData.Role           = result.Role;
        userData.Name           = result.Name " - Copy";
        userData.Area           = result.Area;
        userData.FilePhotoURL1  = result.FilePhotoURL1;
        userData.Email          = email;
        userData.LihatJurnal    = result.LihatJurnal;
        userData.UserDataArea   = result.UserDataArea;
        userData.UserDataMenu   = result.UserDataMenu;
        userData.UserDataGudang = result.UserDataGudang;
        userData.UserDataPerkiraan = result.UserDataPerkiraan;

        try
        {
            _context.UserData.Add(userData);
            await _context.SaveChangesAsync();
        }
        catch(Exception Ex)
        {
            Console.WriteLine("\n ======================== \n");
            Console.WriteLine("\n "   Ex   " \n");
            Console.WriteLine("\n ======================== \n");
        }

        return Json(userData);
    }

CodePudding user response:

You try to create a user with the same Username, which cause user to be the instance of the same user. Calling AddToRoleAsync on the same user cause the error because the user has already had the role. You should try to create user with different email.

  • Related