Bright loading of many for many - EF Core

Hi, I have many different relationships as shown below.

public class order { public int id { get; set; } public virtual ICollection<OrderProducts> Products { get; set; } } public class product { public int id { get; set; } public virtual ICollection<OrderProducts> Orders { get; set; } } public class OrderProducts { public int OrderId { get; set; } public virtual Order Order{ get; set; } public int ProductIdId { get; set; } public virtual Product Product { get; set; } } 

I would like to include (load) all products in my orders, but using the same approach as shown with the client, my product list is populated with OrderProducts, not Product-objects

 public IEnumerable<Order> GetAll() { return dataContext.Orders .Include(order => order.Customer) // now include all products aswell.. } 

I tried things like witout any luck

  .Include(order => order.Products.Where(op => op.OrderId == order.Id).Select(p => p.Product)) 

So if someone can help me here. You can also share any good resources on how to build more advanced lambdas since I am not familiar with this yet.

+5
source share
2 answers

Just use ThenInclude() statement:

 public class order { public int id { get; set; } public virtual IList<OrderProducts> OrderProducts { get; set; } } //... public IEnumerable<Order> GetAll() { return dataContext.Orders .Include(order => order.OrderProducts) .ThenInclude(orderProducts => orderProducts.Product); } 

As indicated here , the many-to-many relationship is not yet implemented. You must load OrderProducts , then Select(orderProducts => orderProducts.Product)

Important: The end of IntelliSense may say that you cannot do this, but you can just create a real assembly and it will work

+14
source

Just to make slander - Robin was right all the time. After reading this https://github.com/aspnet/EntityFramework/issues/6166 and doing some debugging, the object was there all the time .. I just needed to change my [JsonIgnore] abit attributes.

+1
source

Source: https://habr.com/ru/post/1263154/


All Articles