tags:

views:

430

answers:

1

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.

+3  A: 
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
why would you use a "var" when you know exactly what's coming? couldn't you instead use a List of Employee?
Chris Simpson
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
vars are still typed in C# 3.0, it's just syntactic sugar
matt_dev
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
thanks, I tried it and it worked beautifully.
Joel