实体框架中的Linq嵌套投影



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

在下面的代码中没有问题。现在问题有导航属性作为选项。我想只选择选项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 };

最新更新