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

标签 c# entity-framework linq

在 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/

相关文章:

c# - 如何在安装程序之前终止进程?

c# - 基类设置为派生类,无法调用派生类中的方法?

mongodb - 将 No-Sql 与 EF 结合使用

C# LINQ 组合数学 : All Combinations of a Set without the Empty Set

c# - LINQ 中从何处选择的顺序已更改?是什么原因?

c# - 自定义号码选择器?

c# - DAL、模型层、EF 代码优先和业务逻辑,它们如何组合在一起?

c# - 将 List<t> 转换或转换为 EntityCollection<T>

linq - 从枚举填充字典

c# - "is"关键字 : there a difference in these methods?