Craig
Craig

Reputation: 1796

Why projection is not including navigation nested properties in EF Core 2.0?

I have these types

public class Model
{
    public string Name { get; set; }

    public virtual List<Nested> Nested { get; set; }
}

public class Nested
{
    public Guid ModelId { get; set; }
    public virtual Model Model{ get; set; }

    public Guid FurtherNestedId{ get; set; }
    public virtual FurtherNested FurtherNested { get; set; }
}

public class FurtherNested
{
    public Guid Id {get; set;}
    public string Name{ get; set; }
}

I am trying to use these to build a view model as below:

_dbContext.Models.Include(x => x.Nested).ThenInclude(x => x.FurtherNested).Select(x => new {
    Nested= x.Nested
}).ToList();

For some reason this creates a list of objects with Nested properties (as expected) but a list item's Nested property has FurtherNestedId set but not FurtherNested and so I cannot get FurtherNested.Name. IE FurtherNestedId is there but the actual navigation property is not.

But my data context has the includes...

Why is this please?

EDIT: Also worth noting that by moving the toList() up above the .Select() I get exactly what I want, but it takes 3 times as long to execute.

EDIT: I am trying to get something like this:

{
    any other properties that live on Model,
    Nested: [
         furtherNestedId: '',
         furtherNested: { Name: '' }
    ]
}

Upvotes: 1

Views: 657

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32099

Include doesn't work with projection queries. Once you start projecting (Select), you need to continue with Select all the way down.

So try this:

var myModels = _dbContext.Models.Include(x => x.Nested).ThenInclude(n => n.FurtherNested).Select(x => new
            {
                Name = x.Name,
                Nested = x.Nested.Select(n => new
                {
                    FurtherNestedId = n.FurtherNestedId,
                    FurtherNested = n.FurtherNested
                })

            }).ToList();

Hope it will help you.

Upvotes: 2

Related Questions