I have a controller that updates values in a database using Entity Framework. Unfortunately, when I run my application it doesn't seem to work at all. When I put breakpoints in and step through a specific part of the code, it works perfectly.
Here's my controller code:
public ActionResult ManageGame(int id, FormCollection collection, string[] selectedPlayers)
{
var gameToUpdate = db.Games
.Include("Teams")
.Where(g => g.ID == id)
.Single();
if (TryUpdateModel(gameToUpdate, "", null, new string[] { "Players" }))
{
try
{
List<Player> team1Players = generateRandomTeam();
List<Player> team2Players = generateRandomTeam();
If I put a breakpoint here and step through the rest of the code it's fine, otherwise nothing gets saved.
foreach (var team in gameToUpdate.Teams)
{
if (!team1added)
{
team.Players = team1Players;
team1added = true;
}
else
{
team.Players = team2Players;
}
}
db.Entry(gameToUpdate).State = EntityState.Modified;
db.SaveChanges();
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes.");
}
}
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I have a feeling it's the way I'm assigning the new teams to the existing context, but from all the tutorials I've read, this is the way they do it, at least for string values. Does anybody know why I'm getting this bizarre behavior?
*UPDATE* SOLVED
I solved my problem. My hunch was right, I just needed to add team.Players.Clear() before assigning the new group of players to the existing team.
foreach (var team in gameToUpdate.Teams)
{
if (!team1added)
{
team.Players.Clear()
team.Players = team1Players;
team1added = true;
}
else
{
team.Players.Clear()
team.Players = team2Players;
}
}
When I didn't have that, I got a primary key violation exception. Unfortunately I didn't see this exception, because my code was swallowing this as pointed out by DarK. So, after adding the Clear() method everything worked like a charm.