EF LINQ 包括多个和嵌套的实体 [英] EF LINQ include multiple and nested entities
问题描述
好的,我有具有以下层次结构的三层实体:课程 -> 模块 -> 章节
Ok, I have tri-leveled entities with the following hierarchy: Course -> Module -> Chapter
这是原始的 EF LINQ 语句:
Here was the original EF LINQ statement:
Course course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapters))
.Single(x => x.Id == id);
现在,我想包含另一个与课程相关的名为 Lab 的实体.
Now, I want to include another entity called Lab which is associated with a course.
如何包含实验室实体?
我尝试了以下方法,但没有奏效:
I tried the following but it didn't work:
Course course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapters) && i.Lab)
.Single(x => x.Id == id);
关于包含第二个实体的任何想法?
Any ideas on including the 2nd Entity?
任何建议或信息将不胜感激.谢谢!
Any piece of advise or information would be highly appreciated. Thanks!
推荐答案
您是否尝试过仅添加另一个 Include
:
Have you tried just adding another Include
:
Course course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapters))
.Include(i => i.Lab)
.Single(x => x.Id == id);
您的解决方案失败了,因为 Include
没有使用布尔运算符
Your solution fails because Include
doesn't take a boolean operator
Include(i => i.Modules.Select(s => s.Chapters) && i.Lab)
^^^ ^ ^
list bool operator other list
更新要了解更多信息,请下载 LinqPad 并浏览示例.我认为这是熟悉 Linq 和 Lambda 的最快方法.
Update To learn more, download LinqPad and look through the samples. I think it is the quickest way to get familiar with Linq and Lambda.
首先 - Select
和 Include
之间的区别在于,通过 Select,您可以决定什么你想返回(又名投影).Include 是一个 Eager Loading 函数,它告诉实体框架您希望它包含来自其他表的数据.
As a start - the difference between Select
and Include
is that that with a Select you decide what you want to return (aka projection). The Include is a Eager Loading function, that tells Entity Framework that you want it to include data from other tables.
Include 语法也可以是字符串.像这样:
The Include syntax can also be in string. Like this:
db.Courses
.Include("Module.Chapter")
.Include("Lab")
.Single(x => x.Id == id);
但是 LinqPad 中的示例更好地解释了这一点.
But the samples in LinqPad explains this better.
这篇关于EF LINQ 包括多个和嵌套的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!