【问题标题】:How can I populate a collection inside a DTO with LINQ?如何使用 LINQ 填充 DTO 内的集合?
【发布时间】:2014-07-02 08:43:44
【问题描述】:

我创建了以下 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 =&gt; t.TestQuestions) 例如,我是否必须在 TestAndQuestionDTO 中有一个构造函数来创建一个 TestQuestions 集合?

这是我的测试类供参考:

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; }

}

【问题讨论】:

  • 为什么你不能在选择中只做TestQuestions = t.TestQuestions
  • 因为左边的TestQuestions 类只有一个字段,而t.TestQuestions 有很多字段。如果我错了,请纠正我,但我认为我应该将它们一一对应。

标签: c# .net linq dto


【解决方案1】:

您可以像这样使用另一个 Select 转换为您的 Questions 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&lt;&gt; 类型,请将其更改为:

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

【讨论】:

  • 我收到错误消息:'System.Collections.Generic.IEnumerable' 到 'System.Collections.Generic.ICollection'.
  • Test‌​AndQuestionDTO.Questions 是否必须是 ICollection 而不是 IEnumerable
  • 我更喜欢与IEnumerable 一起工作,所以我会改成这样。否则,我已经对我的答案进行了补充。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
相关资源
最近更新 更多