gpt4 book ai didi

c# - Entity Framework 中的 Linq 嵌套投影

转载 作者:行者123 更新时间:2023-12-04 13:41:04 25 4
gpt4 key购买 nike

在 EF 实体的 Linq 投影中,我只能选择所需的属性。

在ex问题下面的代码中。现在问题有导航属性作为选项。我只想选择选项 ID 和选项标题作为嵌套属性

如果我写

options.ToList() 

它将适用于所有属性。

我只想包含 Options.IDOptions.Title

var query = from c in context.Sec_Questions.AsNoTracking()
where c.IsActive == true
select new
{ c.ID, c.QuestionType,
c.Title, c.ControlName,
c.IsNumberOnly,
c.Maxlenghth,
options = c.Options.ToList(),
c.IsMultiple,
c.ControlID,
c.HelpText,
c.IsRequired };
var questions = query.ToList();

但是这段代码不起作用

var query = from c in context.Sec_Questions.AsNoTracking()
where c.IsActive == true
select new
{ c.ID, c.QuestionType,
c.Title, c.ControlName,
c.IsNumberOnly,
c.Maxlenghth,
options = new { c.Options.ID, c.options.Title },
c.IsMultiple,
c.ControlID,
c.HelpText,
c.IsRequired };
var questions = query.ToList();

最佳答案

从这个c.Options.ToList()我了解到Options是一个集合。所以你应该做的是使用 .Select 来投影一个只包含这两个属性的新对象:

var query = from c in context.Sec_Questions
where c.IsActive == true
select new {
c.ID,
c.QuestionType,
c.Title,
c.ControlName,
c.IsNumberOnly,
c.Maxlenghth,
Options = c.Options.Select(o => new { o.ID, o.Title }),
c.IsMultiple,
c.ControlID,
c.HelpText,
c.IsRequired };

关于c# - Entity Framework 中的 Linq 嵌套投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com