2

Writing my first Linq application, and I'm trying to find the best way to do the following:

I want to load the entire employees table at once to populate the cache (used for form autocomplete).

I can do -

var query = from employee in db.Employees select employee;
foreach (Employee e in query)
{
    ...
}

But since this is deferred loading, it generates one query per employee. How can I eager load the entire table?

I've looked into DataLoadOptions but that seems to only work for relationships.

Kev
  • 118,037
  • 53
  • 300
  • 385
Joel
  • 814
  • 2
  • 9
  • 19

1 Answers1

3
var query = db.Employees.ToList();

By the way, this is equivalent to:

var query = (from employee in db.Employees select employee).ToList();

There's no reason to force yourself to use query operators syntax when lambda syntax makes more sense and is shorter.

Side note 1: The type of query object will be List<Employee>, however, there is no difference it terms of generated IL and performance if we explicitly specified it.

Side note 2: It's important to know the query specified in the question is not executed once per employee. It's executed just once and is fetched one by one from database (similar to a SqlDataReader object running a SELECT * FROM Employees query). However, ToList() loads all rows in a list making further queries going to that object get executed at the application itself, not SQL Server.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • why would you use a "var" when you know exactly what's coming? couldn't you instead use a List of Employee? – Chris Simpson Jan 16 '09 at 16:33
  • Chris, it's a subjective topic and kind of religious issue which has been covered in other questions. There is absolutely no difference in the emitted IL (and therefore, performance). It's mostly a matter of style. – Mehrdad Afshari Jan 16 '09 at 16:35
  • vars are still typed in C# 3.0, it's just syntactic sugar – matt_dev Jan 16 '09 at 16:37
  • All depends on the scope of usage and your preferences. This is a fine read on pros/cons: http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c – Kev Jan 16 '09 at 16:37