开发者

Including child Objects in Entityframework

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 开发者_Go百科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...


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.


You cannot use Include() on a projection, try this:

Iquerable<Persons> persons = Context.Persons
                                    .Include("Address")
                                    .Select(x=> new persons{Pkid=x.pkid, FirstName=x.FirstName})
                                    .AsQuerable();

Also you have a naming conflict, you project to a type persons and want to hold the results in an IQueryable named persons - one of them is wrong. Is there a reason you need the projection at all? You could just do

Iquerable<Persons> persons = Context.Persons.Include("Address");


First: Check if lazy loading is enabled or not. I experienced different results when it was enabled. I prefer lazy loading being disabled.

Second: Check this syntax:

result = (From person In context.Persons.Include("Address")).ToList();

P.S.: Useful EF Tips & Tricks : http://blogs.msdn.com/b/alexj/archive/2009/03/26/index-of-tips.aspx

UPDATE:

Include is not working, because your are using it on newly created objects, not the objects available in the context. you should use Include before creating new objects.

Check This:

result = (From person In context.Persons.Include("Address") Select New With {.FirstName = item.FirstName, .AddressValue = item.Address.Value}).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜