Entityframework includes child objects

entity-framework iqueryable linq-to-entities

Question

I want to include child objects on an IQueryable list..

I want to include a child object on selected columns of some table type IQueryable list..

I tried like this:

IQueryable<Persons> persons = Context.Persons.Select(x=> new persons{Pkid=x.pkid, FirstName=x.FirstName}).AsQueryable();

persons= persons.Include("Address");

this include of child objects is not working..anyone please help...where I am doing wrong.. thanks alot...

1
2
11/16/2017 8:29:15 AM

Popular Answer

Include doesn't work with projection. Moreover it is not needed. Just do this:

var query = context.Persons
                   .Select(x => new PersonDto
                       {
                          Id = x.pkid, 
                          FirstName = x.FirstName,
                          Address = x.Address
                       });

Few points here:

  • No Include
  • Address accessed directly in projection, EF will handle this
  • I'm using PersonDto as target of projection. PersonDto has just Id, FirstName and Address.
  • You can project to custom type or anonymous type but you cannot project to entity type (the mapped type) - it doesn't work and it throws exception.
  • If you want to use mapped type you can't return only selected scalar columns - all columns will always be loaded. Only navigation properties can be loaded selectively. To overcome this people sometimes use Table splitting but that is something which works if you can divide your big entity into disjunct entities. In your scenario use just projection.
3
4/9/2011 9:45:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow