In a Linq projection for an EF entity, I am able to select only properties which are required.
In the code below ex questions. Now question has navigation property as options. I want to select only option id and option title as nested property
If I write
options.ToList()
it will work with all properties.
I want only Options.ID
and Options.Title
to be included
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();
But this code doesn't work
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();
From this c.Options.ToList()
I understand that Options
is a collection. So what you should do is use .Select
to project a new object containing just those two properties:
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 };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.