Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Nested Projections in Entity Framework

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();
like image 256
user3815413 Avatar asked Oct 16 '25 05:10

user3815413


1 Answers

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 };
like image 141
Gilad Green Avatar answered Oct 18 '25 21:10

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!