2

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.

4

1 回答 1

3

看起来其他人也遇到了和你一样的问题。查看这些链接:C# 代码仅在逐步执行时给出预期结果?,代码只有在使用调试器单步执行时才能正确运行?

所以,如果你不止一次地实例化 Random 类,你会得到一些奇怪的结果。

编辑:

从您的代码看来,您正在使用异常。你可以注释掉 try-catch 并在不调试的情况下运行它,看看它是否抛出任何异常?

于 2013-02-17T01:39:16.793 回答