I'm trying to remove an object and all its related objects without retrieving the whole entity from the database first using Entity Framework 6.2.0
.
The object is a team. A team can have many users as well as many players. The relation to a single player is m:n and realised through an intermediate table called tblPlayerInTeam
.
So I want to remove the intermediate entry but not the tblPlayer-entry.
This is what my code currently looks like:
var teamIds = new[] { new Guid("2007d05f-d61d-428b-b21f-0e8a9ff660a2") };
foreach (var teamId in teamIds)
{
var teamToDelete = new tblTeam { TeamId = teamId };
// mark the team as Deleted
dbContext.Entry(teamToDelete).State = System.Data.Entity.EntityState.Deleted;
// get the primary keys of tblPlayerInTeam
var teamPlayerIds = dbContext.tblPlayerInTeam.Where(pit => pit.PlayerInTeamTeamId == teamId).Select(pit => pit.PlayerInTeamId);
foreach (var teamPlayerId in teamPlayerIds)
{
var playerToDelete = new tblPlayerInTeam { PlayerInTeamId = teamPlayerId };
// mark the playerInTeam as Deleted
dbContext.Entry(playerToDelete).State = System.Data.Entity.EntityState.Deleted;
}
// get the primary keys of tblTeamUser
var teamUserIds = dbContext.tblTeamUser.Where(tu => tu.TeamUserTeamId == teamId).Select(tu => tu.TeamUserId);
foreach (var teamUserId in teamUserIds)
{
var userToDelete = new tblTeamUser { TeamUserId = teamUserId };
// mark the teamUser as Deleted
dbContext.Entry(userToDelete).State = System.Data.Entity.EntityState.Deleted;
}
}
SaveChanges(); // <-- here I get the error
The DELETE statement conflicted with the REFERENCE constraint "FK_tblTeamUser_tblTeam".
From the generated SQL I can tell, that the tblPlayerInTeam
entries are going to be deleted but tblTeamUser
-entries are completetly ignored.
If I only run the last part (for the team-users) the SQL generated is fine. I don't see why it's ignored otherwise.
Same when I remove the playerInTeam part. It only generates the DELETE-statement for the team but not for the team-users.
I already tried to change the order so the team would be the last one to be removed (marked as Deleted). But still the same error.