实体框架中的Linq嵌套预测

时间:2016-10-10 11:56:28

标签: c# entity-framework 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();

1 个答案:

答案 0 :(得分:2)

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