This question led me to wonder the following:
What are the 'Gotchas' associated with tacking on a ToList() to a Linq-to-Sql query?
I'm equally interested in best practices and anecdotes.
This question led me to wonder the following:
What are the 'Gotchas' associated with tacking on a ToList() to a Linq-to-Sql query?
I'm equally interested in best practices and anecdotes.
Disregarding transactions:
using (PlayerDataContext context = new PlayerDataContext())
{
var players = context.Players.ToList();
MethodThatUnexpectedlyTakes25SecondsToComplete();
Console.WriteLine(players.Count()); // Outputs a stale count
}
The big one is the loss of deferred execution. A linq query normally doesn't actually do anything until you iterator over the results. Calling .ToList() iterates over the results, and so will run the query right away.
Compromising linq-to-sql's ability to optimize:
using (PlayerDataContext context = new PlayerDataContext())
{
// suboptimal
var players = context.Players.ToList();
Console.WriteLine(players.Count());
// optimal
var playerCount = context.Players.Count();
Console.WriteLine(playerCount);
}