Eager Load many to Many - EF Core

asp.net-core c# entity-framework lambda

Question

Hello I have a many to many relationship set up like following.

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 (Eager load) all products into their orders, but when using same approach like shown with customer, my product list get populated with OrderProducts-objects and not Product-objects

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

I have tried stuff like witout any luck

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

So would appreciate if someone could help me out here.. You'r also most welcome to share any good resources on how to construct more advanced lambdas, since i'm not that familiar with this yet..

1
19
1/22/2017 5:45:36 AM

Accepted Answer

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 stated here, many-to-many relation is not yet implemented. You have to load your OrderProducts then Select(orderProducts => orderProducts.Product)

Important: IntelliSense completion might tell you can't do this, but you can, just make a real build and it will work

41
10/19/2017 6:11:55 PM

Popular Answer

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



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