我创建了以下DTO:
public class TestAndQuestionDTO
{
public string Name { get; set; }
public int QuestionsCount { get; set; }
public ICollection<TestAndQuestionDTO.Questions> TestQuestions { get; set; }
public class Questions
{
public Guid QuestionUId { get; set; }
}
}
我试图用LINQ填充它,但我仍然坚持如何填充内部的问题类。
这是我到目前为止所做的:
var result = await db.Tests
.Include(t => t.TestQuestions)
.Where(t => t.TestId == id)
.Select(t => new TestAndQuestionDTO
{
Name = t.Title,
TestQuestions = new TestAndQuestionDTO.Questions
{
QuestionUId = t.TestQuestions. ????
}
})
.ToListAsync();
有人可以告诉我如何使用从我的集合中返回的数据填充TestQuestions集合字段:.Include(t => t.TestQuestions)
我是否必须在TestAndQuestionDTO中创建一个构造函数来创建TestQuestions的集合?
这是我的Test类供参考:
public partial class Test
{
public Test()
{
this.TestQuestions = new HashSet<TestQuestion>();
}
public int TestId { get; set; }
public string Title { get; set; }
public virtual ICollection<TestQuestion> TestQuestions { get; set; }
}
答案 0 :(得分:3)
您可以使用其他选择转换为您的问题DTO:
var result = await db.Tests
.Include(t => t.TestQuestions)
.Where(t => t.TestId == id)
.Select(t => new TestAndQuestionDTO
{
Name = t.Title,
TestQuestions = t.TestQuestions.Select(tq => new TestAndQuestionDTO.Questions
{
QuestionUId = tq.QuestionUId,
//fill in your Questions DTO here
})
})
.ToListAsync();
如果您需要TestAndQuestionDTO.Questions
为ICollection<>
类型,请将其更改为:
var result = await db.Tests
.Include(t => t.TestQuestions)
.Where(t => t.TestId == id)
.Select(t => new TestAndQuestionDTO
{
Name = t.Title,
TestQuestions = new Collection<TestAndQuestionDTO.Questions>(
t.TestQuestions.Select(tq => new TestAndQuestionDTO.Questions
{
QuestionUId = tq.QuestionUId,
//fill in your Questions DTO here
}).ToList())
})
.ToListAsync();