Search code examples
c#entity-frameworkeager-loading

Using Include() with anonymous types in Entity Framework


I am trying to eager load some properties using Include method as following:

var dbData = dbContext.Locators.Include(x => x.PhysicalObjects.Select(p => p.Parent)).Include(x => x.PhysicalObjects.Select(p =>p.Type.AllowedSubTypes))
                .Where(x => x.id==1)).Select(x => new
                {
                    newContainer = x.PhysicalObjects.Where(p => p.Id== newContainerId).FirstOrDefault(),
                    phyiscalObject = x.PhysicalObjects.Where(p => p.Id == id).FirstOrDefault()
                }).FirstOrDefault();

But it returns Parent and Type properties as null(I checked database they are not null).

So how can I eager load those properties?

P.S

I am using Entity Framework V6.1.3


Solution

  • Depending on DevilSuichiro's comment above the query will be like this:

     var dbData = dbContext.Locators.Include(x => x.PhysicalObjects.Select(p => p.Parent)).Include(x => x.PhysicalObjects.Select(p =>p.Type.AllowedSubTypes))
                    .Where(x => x.Id==1)).Take(2).ToList().Select(x => new
                    {
                        newContainer = x.PhysicalObjects.Where(p => p.Id== newContainerId).FirstOrDefault(),
                        phyiscalObject = x.PhysicalObjects.Where(p => p.Id == id).FirstOrDefault()
                    }).FirstOrDefault();
    

    It worked for me, but I will still be waiting for better answer if any.