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

发布于 2024-07-11 19:22:04 字数 313 浏览 7 评论 0原文

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

我想立即加载整个员工表以填充缓存(用于表单自动完成)。

我可以这样做 -

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

但由于这是延迟加载,它会为每个员工生成一个查询。 如何立即加载整个表?

我研究过 DataLoadOptions 但这似乎只适用于关系。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可爱暴击 2024-07-18 19:22:04
var query = db.Employees.ToList();

顺便说一句,这相当于:

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

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

旁注 1query 对象的类型将为 List,但是,在生成的 IL 和性能方面没有区别如果我们明确指定它。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文