I'm using Entity Framework for a very small database keeping track of game states in a card game. The Game has players which has cards, my models look like this:
public class Game
{
public int Id { get; set; }
public DateTime DateTime { get; set; }
public virtual List<Player> Players { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual List<Card> Cards { get; set; }
}
public class Card
{
public int Id { get; set; }
public string Value { get; set; }
public string Suite { get; set; }
}
It's not the best design (I know) but it gets the work done. Anyhow now I wanted to show all the games (and in effect their players and their cards) and I thought my lazy loading it would be as simple as writing:
public List<Game> GetAllGames()
{
using (var db = new DatabaseContext())
{
return db.Games.ToList();
}
}
But debugging the code, I notice that the Players attribute inside each Game object throws something called ObjectDisposedException. It seems to be that it has to do with the using statement with the db context. I searched around and found questions here on SO before regarding this and the only option seems to write LINQ to remove the virtual keyword and write LINQ instead (and I'm not sure what this should be for the things I want). So what is the purpose of lazy loading if there is no use of it outside the using statement?
DatabaseContextso connection is closed and EF cannot go to database to do that. Either use eager loading (Include) or don't dispose context while you still need it.