'The DELETE statement conflicted with a REFERENCE constraint

I have the following entities.

public class GroupUser
{
    public long Id { get; set; }
    public Group Group { get; set; }
    public long GroupId { get; set; }
    public string UserId { get; set; }
    public User User { get; set; }
}

public class User : IdentityUser
{
    public List<GroupUser> GroupUsers { get; set; }

}
public class Group
{
    public long Id { get; set; }
    public List<GroupUser> GroupUsers { get; set; }
}

I get the delete The DELETE statement conflicted with the REFERENCE constraint "FK_GroupUsers_AspNetUsers_UserId". The conflict occurred in database "db", table "dbo.GroupUsers", column 'UserId' when I try to delete a user even though I make sure i delete existing entities referencing the id of the user before actually deleting the user like below;

var user = await _userManager.FindByEmailAsync(email);
var groupUsers = _context.GroupUsers.Where(c => c.UserId == user.Id);
_context.RemoveRange(groupUsers);
await _context.SaveChangesAsync();

_context.Remove(user);
await _context.SaveChangesAsync();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source