如何在LINQ中加载整个SQL表?

时间:2023-01-03 19:32:51

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

编写我的第一个Linq应用程序,我正在尝试找到执行以下操作的最佳方法:

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

我想一次加载整个employees表来填充缓存(用于表单自动完成)。

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.

我查看了DataLoadOptions,但这似乎只适用于关系。

1 个解决方案

#1


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.

当lambda语法更有意义且更短时,没有理由强迫自己使用查询运算符语法。

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.

旁注1:查询对象的类型将是List ,但是,如果我们明确指定它,则生成的IL和性能的条款没有区别。

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.

附注2:重要的是要知道每个员工不会执行问题中指定的查询。它只执行一次并从数据库中逐个获取(类似于运行SELECT * FROM Employees查询的SqlDataReader对象)。但是,ToList()加载列表中的所有行,使得进入该对象的进一步查询在应用程序本身而不是SQL Server上执行。

#1


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.

当lambda语法更有意义且更短时,没有理由强迫自己使用查询运算符语法。

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.

旁注1:查询对象的类型将是List ,但是,如果我们明确指定它,则生成的IL和性能的条款没有区别。

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.

附注2:重要的是要知道每个员工不会执行问题中指定的查询。它只执行一次并从数据库中逐个获取(类似于运行SELECT * FROM Employees查询的SqlDataReader对象)。但是,ToList()加载列表中的所有行,使得进入该对象的进一步查询在应用程序本身而不是SQL Server上执行。