我创建了以下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来填充它,但是我仍然坚持如何填充内部的Questions类.
这是我到目前为止的内容:
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; }
}
解决方法:
您可以使用另一个“选择”将其转换为“问题” 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();