1

I have 3 model classes as follows -

    class Product
    {
      ...
    }

    class OrderDetails
    {
      ...
      public int ProductId { get; set; }
      [ForeignKey("ProductId")]
      public virtual Product Product { get; set; }

      public int OrderId { get; set; }
      [ForeignKey("OrderId")]
      public virtual Order Order { get; set; }
    }

    class Order
    {
      ...
      public virtual ICollection<OrderDetails> OrderDetailsList { get; set; }
    }

When I fetch the details from the context like as follows -

Order order = await _dbContext.Orders.Include(x => x.OrderDetailsList).FirstOrDefault(x => x.Id == orderId);

I would like to do the early loading of the Product for each data in OrderDetailsList as well when I fetch the Order, but I'm unable to achieve this.

Raj
  • 417
  • 1
  • 3
  • 17
  • `ThenInclude` appears to be what you want if you're using EF Core: https://learn.microsoft.com/en-us/ef/core/querying/related-data#including-multiple-levels – Prime Jul 13 '19 at 06:19
  • 1
    For EF 6 this answer may help: https://stackoverflow.com/a/10823103/1481699 – Prime Jul 13 '19 at 06:20
  • I know the concept of `Include` and `ThenInclude`. I can do the following with that - `Fetch Object1 > Include Object2 > Include Object3` However, what I want to achieve is the following - `Fetch Object1 > Include List1 > Include Object2 for each product inside the List1` – Raj Jul 13 '19 at 06:21
  • @AlphaDelta, I tried this but it throws the following exception - `The Include property lambda expression 'x => {from OrderDetails y in x.OrderDetailsList select [y].Product}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'` – Raj Jul 13 '19 at 06:27
  • @Raj Please read the docs how to use ThenInclude - knowing the concept is not enough and your ThenInclude expression is far away from the docs – Sir Rufo Jul 13 '19 at 07:02

2 Answers2

0

Does this work?

Order order = await _dbContext.Orders
          .Include(x => x.OrderDetailsList.Select(od=>od.Product))
          .FirstOrDefault(x => x.Id == orderId);
Siderite Zackwehdex
  • 6,293
  • 3
  • 30
  • 46
0

this is working fine with me, please try it.

 _dbContext.Orders.Include(s => s.OrderDetailsList.Select(e => e.Product));