如何在 LINQ 中预加载整个 SQL 表?
编写我的第一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
顺便说一句,这相当于:
当 lambda 语法更有意义且更短时,没有理由强迫自己使用查询运算符语法。
旁注 1:
query
对象的类型将为List
,但是,在生成的 IL 和性能方面没有区别如果我们明确指定它。旁注 2:重要的是要知道问题中指定的查询不是每个员工执行一次。 它仅执行一次,并从数据库中逐个获取(类似于运行
SELECT * FROMEmployees
查询的SqlDataReader
对象)。 但是,ToList()
加载列表中的所有行,从而使针对该对象的进一步查询在应用程序本身(而不是 SQL Server)上执行。By the way, this is equivalent to:
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 beList<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 aSELECT * 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.