Joel
Joel

Reputation: 854

How to Eager Load entire SQL table in LINQ?

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.

Upvotes: 2

Views: 1318

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

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.

Upvotes: 3

Related Questions