如何使用LINQ填充DTO中的集合?

本文关键字:集合 DTO 何使用 LINQ 填充 | 更新日期: 2023-09-27 18:11:10

我创建了以下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; }
}

如何使用LINQ填充DTO中的集合?

您可以使用另一个Select来转换为您的问题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.QuestionsICollection<>类型,将其更改为:

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();