LINQ-to-SQL是否支持可组合查询? [英] Does LINQ-to-SQL Support Composable Queries?

查看:60
本文介绍了LINQ-to-SQL是否支持可组合查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为非C#精明的程序员,我对LINQ查询的评估语义感到好奇,如下所示:

Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:

var people = from p in Person
             where p.age < 18
             select p

var otherPeople = from p in people
                  where p.firstName equals "Daniel"
                  select p

假设Person是定义agefirstName字段的ADO实体,从数据库的角度来看,这将做什么?具体来说,是否会运行people查询以生成内存中的结构,然后由otherPeople查询对其进行查询?还是otherPeople的构造只是从people中提取有关查询的数据,然后生成一个新的数据库对等查询?那么,如果我遍历这两个查询,将执行多少个SQL语句?

Assuming that Person is an ADO entity which defines the age and firstName fields, what would this do from a database standpoint? Specifically, would the people query be run to produce an in-memory structure, which would then be queried by the otherPeople query? Or would the construction of otherPeople merely pull the data regarding the query from people and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?

推荐答案

它们是可组合的.之所以可以这样做,是因为LINQ查询实际上是表达式(作为数据的代码),LINQ-to-SQL之类的LINQ提供程序可以评估并生成相应的SQL.

They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL.

由于LINQ查询的计算是延迟的(例如,直到您遍历元素时才会执行),因此显示的代码实际上不会触及数据库.直到您遍历其他人,否则人们才会生成并执行SQL.

Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.

这篇关于LINQ-to-SQL是否支持可组合查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆