删除相关实体而不从数据库

时间:2018-01-31 10:32:21

标签: c# entity-framework

我正在尝试删除对象及其所有相关对象,而不首先使用Entity Framework 6.2.0从数据库中检索整个实体。

该对象是一个团队。一个团队可以拥有许多用户以及许多玩家。与单个玩家的关系是m:n,并通过名为tblPlayerInTeam的中间表实现。 所以我想删除中间条目,但不删除tblPlayer条目。

这就是我的代码目前的样子:

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
  

DELETE语句与REFERENCE约束“FK_tblTeamUser_tblTeam”冲突。

从生成的SQL我可以看出,tblPlayerInTeam条目将被删除,但tblTeamUser - 条目被完全忽略。 如果我只运行最后一部分(对于团队用户),则生成的SQL很好。我不明白为什么它会被忽略。 删除playerInTeam部分时也一样。它只为团队生成DELETE语句,但不为团队用户生成。

我已经尝试更改顺序,因此团队将是最后一个被删除(标记为已删除)。但仍然是同样的错误。

0 个答案:

没有答案