在 EF 实体的 Linq 投影中,我只能选择所需的属性。
在ex问题下面的代码中。现在问题有导航属性作为选项。 我只想选择选项 ID 和选项标题作为嵌套属性
如果我写
options.ToList()
它将适用于所有属性。
我只想包含 Options.ID
和 Options.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/