创建副本的多对多关系
本文关键字:关系 副本 创建 | 更新日期: 2023-09-27 18:07:26
我正在创建一个涉及三个表的多对多关系,一个表用于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();
}
}
}
我觉得一个简单的函数我不知道应该解决这个问题,但我很难找到我需要的东西。如果有人问这个问题,我很抱歉,我看了,但找不到像这样具体的东西。
谢谢。
您可能忘记将附加实体添加到dataGame
:
var pData = Context.Players.Add(playerData);
dataGame.Players.Add(pData);
Context.SaveChanges();
实体必须来自数据库,而不是新创建的实例。
最后我成功了:
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();
}