多对多关系创建重复

时间:2015-08-12 14:59:57

标签: c# entity-framework

我正在创建一个多对多关系,它涉及三个表,一个用于Game对象的表和一个用于Player对象的表。

每当我创建一个新游戏时,应该引用现有玩家(除非涉及新玩家),现有玩家的新重复玩家会被创建...我创建了一个功能来尝试解决这个问题...它看起来像这样。我认为我已接近解决问题,但我不知道如何将其放入else代码块以使游戏映射到现有玩家。

private void SaveNewPlayers(Common.Game newGame, Data.Game dataGame)
{
    foreach (var player in newGame.Players)
    {
        var isNewPlayer = player.PlayerId < 1;  //The reason I do this is because on the front-end, 
//when a new player is written in rather than selected they receive a negative ID so they can be distinguished
        var playerData = MapToData(player); //This just converts the front end Common.Player 
//to a replica Data.Player object so it's database ready

        if (isNewPlayer)
        {
            Context.Players.Add(playerData);
            dataGame.Players.Add(playerData);
            Context.SaveChanges();
        }
        else
        {


            //Context.Players.Add(playerData);
            //Context.SaveChanges(); //Doing this adds clone Players to the database but not the relational database

            // dataGame.Players.Add(playerData); //Doing this adds clone Players and relationship to the database
            //Context.SaveChanges();


        }
    }

}

我觉得这是一个我不知道应该解决的简单功能,但我很难找到我需要的东西。道歉,如果有人问过,我看了,但找不到具体的东西。

感谢。

2 个答案:

答案 0 :(得分:1)

您可能忘记将附加的实体添加到dataGame

var pData = Context.Players.Add(playerData);
dataGame.Players.Add(pData);
Context.SaveChanges();

实体必须来自db而不是一些新建的实例。

答案 1 :(得分:0)

最终为我工作的是什么:

private void SaveNewPlayers(Common.Game newGame, Data.Game dataGame)
{
    foreach (var player in newGame.Players)
    {
        var isNewPlayer = player.PlayerId < 1; 
        var playerData = MapToData(player);
        if (isNewPlayer)
        {
            Context.Players.Add(playerData);
            dataGame.Players.Add(playerData);
            Context.SaveChanges();
        }
        else
        {
            EditPlayer(player, dataGame);
        }
    }

}

然后创建了这个函数

    public void EditPlayer(Common.Player alteredPlayer, Data.Game thisGame)
    {
        var playerData = Context.Players.Where(p => p.PlayerId == alteredPlayer.PlayerId).First();

        playerData.PlayerId = alteredPlayer.PlayerId;
        playerData.Goals = alteredPlayer.Goals
        /*etc... etc...*/
        playerData.Games = playerData.Games;
        playerData.Games.Add(thisGame);

        Context.SaveChanges();
    }