LINQ:将查询表达式转换为使用 lambda
我正在尝试将 LINQ To Entities 查询重写为表达式。我的模型是一所可以有很多人的学校。人员继承给教师、学生等。
以下查询对我有用:
IQueryable<DAL.TEACHER> teacher =
from p in School
select p.PERSON as ESBDAL.TEACHER;
我如何将其写为查询表达式?我的想法是这样的:
IQueryable<DAL.TEACHER> teacher =
School.Select(x=>x.PERSON) as IQueryable<DAL.TEACHER>;
不幸的是这个声明不起作用。我是否误解了 .Select()
?
I'm trying to rewrite a LINQ To Entities query to an expression. My model is a School which can have many Persons. Persons are inherited out to teachers, students, etc.
The following query works for me:
IQueryable<DAL.TEACHER> teacher =
from p in School
select p.PERSON as ESBDAL.TEACHER;
How would I write this as a query expression? I thought something like:
IQueryable<DAL.TEACHER> teacher =
School.Select(x=>x.PERSON) as IQueryable<DAL.TEACHER>;
Unfortunately this statement doesn't work. Am I misunderstanding the .Select()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它实际上应该是:
记住,您正在尝试将
PERSON
转换为TEACHER
,因此它会进入委托内部。School.Select(x => x.PERSON)
本身的结果实际上是一个IEnumerable
,它不能转换为IEnumerable;
。另一件事 - 如果某些
PERSON
实例实际上不是TEACHER
(即它们是STUDENT
),那么您最终会输出中包含null
引用。如果PERSON
可以是多种类型,您可能会想这样写出来:这实际上会过滤掉所有 的
PERSON
实体tTEACHER
,因此您只能返回序列中的TEACHER
实例(无空值)。另请注意,
from x in y
语法是“查询”(特别是查询理解语法)。第二种形式是 lambda 语法。It should actually be:
Remember, you're trying to cast the
PERSON
to aTEACHER
, so it goes inside the delegate. The result ofSchool.Select(x => x.PERSON)
by itself is actually anIEnumerable<PERSON>
, which is not convertible toIEnumerable<TEACHER>
.One more thing - if some
PERSON
instances are not actuallyTEACHER
s (i.e. they areSTUDENT
s instead), you're going to end up withnull
references in the output. IfPERSON
can be more than one type, you would probably want to write it out like this instead:This will actually filter out all of the
PERSON
entities that aren'tTEACHER
s, so you only get backTEACHER
instances in the sequence (no nulls).Also note that the
from x in y
syntax is the "query" (specifically query comprehension syntax). The second form is lambda syntax.