ThenInclude not working for an Entity Framework LINQ query

c# entity-framework-core linq

Question

I have a database model like this:

public class Customer
{
    public int CustomerId{ get; set; }

    public int OrderId { get; set; }
    public ICollection<Order> Orders { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    public int Amount { get; set; }

    public int ProductId { get; set; }
    public Product Product { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

So we have a customer which can do an order. This order includes a product and this includes a name. I'm now trying to return the complete model with a linq statement like the following:

_db.Customer.Include(c => c.Orders).ThenInclude(o => o.Product).SingleOrDefaultAsync();

But ThenInclude(o => o.Product) doesn't function because Orders is an ICollection. Greetings from Germany and thanks in advance for any help.

1
5
3/14/2017 2:14:25 PM

Accepted Answer

The EF Core equivalent syntax of EF6

.Include(x => x.Tests.SelectMany(z => z.PupilsTests))

is

.Include(x => x.Tests).ThenInclude(x => x.PupilsTests)

Note that there seems to be a VS Intellisense issue inside the ThenInclude, so just type the above and it will compile successfully and work.

Also please note that EF Core processes collection includes differently (does not use single query as in EF6), so the above would generate and execute 3 SQL queries.

Update: The VS Intellisense issue now is specifically mentioned in the EF Core documentation under Including multiple levels section:

Note!

Current versions of Visual Studio offer incorrect code completion options and can cause correct expressions to be flagged with syntax errors when using the ThenInclude method after a collection navigation property. This is a symptom of an IntelliSense bug tracked at https://github.com/dotnet/roslyn/issues/8237. It is safe to ignore these spurious syntax errors as long as the code is correct and can be compiled successfully.

5
8/1/2018 12:33:21 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