/// <summary> /// Method to update materials supports of a game /// </summary> /// <param name="selectedMaterials">materials to apply</param> /// <param name="gameToUpdate">Game that needs changes</param> public void UpdateGamesMaterialSupport(string[] selectedMaterials, Game gameToUpdate) { if (selectedMaterials == null) { gameToUpdate.MaterialSupportsGames = new List <MaterialSupportsGames>(); return; } var selectedMs = new HashSet <string>(selectedMaterials); var gamesMs = new HashSet <int> (gameToUpdate.MaterialSupportsGames.Select(c => c.MaterialSupport.Id)); foreach (var ms in _context.MaterialSupport) { if (selectedMs.Contains(ms.Id.ToString())) { if (!gamesMs.Contains(ms.Id)) { gameToUpdate.MaterialSupportsGames.Add(new MaterialSupportsGames() { GameId = gameToUpdate.Id, MaterialSupportId = ms.Id }); } } else { if (gamesMs.Contains(ms.Id)) { MaterialSupportsGames msToRemove = gameToUpdate.MaterialSupportsGames.FirstOrDefault(i => i.MaterialSupportId == ms.Id); _context.Remove(msToRemove); } } } }
public async Task <IActionResult> Create([Bind("Id,Name,Description,MinPlayer,MaxPlayer,MinimumAge,GameTime,Price,ReleaseDate,BuyLink,VideoLink,PictureLink,Validate,DifficultyId,IllustratorId,EditorId")] Game game, string[] selectedThemes, string[] selectedMs, string[] selectedMecha) { if (game.EditorId == -1) { game.EditorId = null; } if (game.DifficultyId == -1) { game.DifficultyId = null; } if (game.IllustratorId == -1) { game.IllustratorId = null; } if (selectedMecha != null) { game.MechanismsGames = new List <MechanismsGames>(); foreach (var mecha in selectedMecha) { var mechaToAdd = new MechanismsGames() { GameId = game.Id, MechanismId = int.Parse(mecha) }; game.MechanismsGames.Add(mechaToAdd); } } if (selectedMs != null) { game.MaterialSupportsGames = new List <MaterialSupportsGames>(); foreach (var ms in selectedMs) { var msToAdd = new MaterialSupportsGames() { GameId = game.Id, MaterialSupportId = int.Parse(ms) }; game.MaterialSupportsGames.Add(msToAdd); } } if (selectedThemes != null) { game.ThemesGames = new List <ThemesGames>(); foreach (var t in selectedThemes) { var themeToAdd = new ThemesGames() { GameId = game.Id, ThemeId = int.Parse(t) }; game.ThemesGames.Add(themeToAdd); } } if (ModelState.IsValid) { _context.Add(game); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } else { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); var test = errors; } ViewDataRelationOtM(game); ViewDataRelationMtM(game); return(View(game)); }