【发布时间】:2020-03-01 20:52:41
【问题描述】:
我有以下运行良好的 LINQ 查询:
public IList<Course> GetEmployeeCourses(int id) {
var employeeCourses = Context.Employees
.Where(e => e.Id == id)
.SelectMany(e => e.employeeCourses.Select(ec => ec.Course))
.ToList();
return employeeCourses;
}
问题是,我现在还需要在返回 Course 数组时包含所选课程的子数组 (Urls)。
类似:
public IList<Course> GetEmployeeCourses(int id) {
var employeeCourses = Context.Employees
.Where(e => e.Id == id)
.SelectMany(e => e.employeeCourses.Select(ec => ec.Course))
.Include(c => c.Urls)
.ToList();
return employeeCourses;
}
这样返回 JSON:(尽管 Course 模型有超过 15 个属性)
[
{
"Name": "Course1",
"Type": "Maths",
"Location": "Block C",
"Urls": [
{
"Link": "https://url1forcourse1.com"
},
{
"Link": "https://url2forcourse1.com"
}
]
}
{
"Name": "Course2"
"Type": "Computer Science",
"Location": "Block A",
"Urls": [
{
"Link": "https://url1forcourse2.com"
},
{
"Link": "https://url2forcourse2.com"
}
]
},
{
"Name": "Course3"
"Type": "The Art of Dish Washing",
"Location": "Block E",
"Urls": [
{
"Link": "https://url1forcourse3.com"
},
{
"Link": "https://url2forcourse3.com"
}
]
}
]
如何以最有效的方式实现这一目标?目前我似乎根本无法获取名为“Urls”的子数组,它始终为空。
另外,我正在使用 Fluent API 和这个 EmployeeCourse 配置:
ToTable("EmployeeCourses");
HasKey(q => new { q.CourseId, q.Employee.Id})
HasRequired(x => x.Employee)
.WithMany(x => x.EmployeeCourses)
.HasForeignKey(x => x.CourseId);
HasRequired(x => x.Course)
.WithMany(x => x.EmployeeCourses)
.HasForeignKey(x => x.EmployeeId);
【问题讨论】:
-
如果这是
EF6或EF Core?请具体并相应标记。
标签: c# linq entity-framework-6