如何在LINQ查询中包括多个层次? [英] How can I include more than one level deep in a LINQ query?
问题描述
我有三个用类表示的SQL表,并且我想让Entity Framework 6加入这些表,以便获得Exam
,Test
和UserTest
表的所有详细信息,其中UserTest.UserID
是0
或X
.
I have three SQL tables that are represented by classes and I would like to have Entity Framework 6 join these tables so I get all the details of the Exam
, Test
and UserTest
tables where the UserTest.UserID
is 0
or X
.
我已经建立了一个存储库,该存储库适用于简单查询,但是我无法在问题底部加入LINQ中的UserTest
类.
I have already set up a respository and this works for simple queries however I am unable to join the UserTest
class in the LINQ at the bottom of the question.
这是我的课程:
public class Exam
{
public int ExamId { get; set; }
public int SubjectId { get; set; }
public string Name { get; set; }
public virtual ICollection<Test> Tests { get; set; }
}
public class Test
{
public int TestId { get; set; }
public int ExamId { get; set; }
public string Title { get; set; }
public virtual ICollection<UserTest> UserTests { get; set; }
}
public class UserTest
{
public int UserTestId { get; set; }
public string UserId { get; set; }
public int TestId { get; set; }
public int QuestionsCount { get; set; }
}
我想做的是查询看起来像这样的东西:
What I would like to do is to have a query that looks something like this:
var exams = _examsRepository
.GetAll()
.Where(q => q.SubjectId == subjectId)
.Include(q => q.Tests )
.Include(q => q.Tests.UserTests) // Error on this line
.ToList();
但是,这并不能让我在VS2013中包含UserTests
.
But it's not letting me include UserTests
in VS2013.
更新:
这是我第一次尝试的查询:
Here is the query I first tried:
var userTests = _userTestsRepository
.GetAll()
.Include(t => t.Test)
.Include(t => t.Test.Exam)
.Where(t => t.UserId == "0" || t.UserId == userId);
这似乎很有效,但是当我查看输出时,看到的是这样的:
This one seemed to work however when I looked at the output I saw something like this:
[{"userTestId":2,
"userId":"0",
"testId":12,
"test":{
"testId":12,"examId":1,
"exam":{
"examId":1,"subjectId":1,
"tests":[
{"testId":13,"examId":1,"title":"Sample Test1",
"userTests":[
{"userTestId":3,
"userId":"0",
请注意,这种情况开始重复出现,并带来了比我预期更多的数据
Note that this starts to repeat and bring back a lot more data than I expected
推荐答案
这是因为Tests是一个集合,而不仅仅是一个对象,因此它没有UserTests属性.您可以使用lambda来指定多个孩子而不是一个孩子的孙子:
That's because Tests is a collection and not just a single object, so it doesn't have a UserTests property. You use a lambda to specify grandchildren of multiple children rather than a single child:
var exams = _examsRepository
.GetAll()
.Where(q => q.SubjectId == subjectId)
.Include(q => q.Tests.Select(t => t.UserTests))
.ToList();
请注意,不需要两个Include调用,因为如果要包括孙子项,则隐式包括子项.
Note that there's no need for two Include calls because the children are implicitly included if you're including the grandchildren.
这篇关于如何在LINQ查询中包括多个层次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!