Yuan
Yuan

Reputation: 2800

Partial eager loading child entity (load specific fileds)

I searched a bit and understands that I can use projection to partially load an entity , the question becomes is there a way to partially eager loading a child? Say I have the following

Entity A has

Id
Name
EntityB

and Entity B has

Id
StuffToBeLoaded1
StuffToBeLoaded2
OtherStuffNotToBeLoaded

How can I load A with B , and B only has stuffToBeLoaded1 and stuffToBeLoaded2? I guess I cannot call .Inlucde("EntityB") otherwise it is fully loaded, is it?

Upvotes: 0

Views: 372

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

You must use custom query with a projection. If EntityB property represents collection you can use something like:

var query = from a in context.EntitiesA
            select new 
               {
                  a.Id,
                  a.Name,
                  Bs = a.EntityB.Select(b => new { 
                       b.StuffToBeLoaded1, 
                       b.StuffToBeLoaded2 
                  })
               };

If EntityB is not a collection navigation property you can simply use:

var query = from a in context.EntitiesA
            select new 
               {
                  a.Id,
                  a.Name,
                  a.EntityB.StuffToBeLoaded1, 
                  a.EntityB.StuffToBeLoaded2 
               };           

Upvotes: 3

Related Questions