C#C
C#2y ago
Mario K.

How to perform nested one-to-many join in LINQ

I apologize if this is stupid, but how to return an IEnumerable<Receipt> that contains Product in this case:

// Each Receipt can have many ReceiptDetals
public class Receipt
{
public int Id { get; set; }
public virtual ICollection<ReceiptDetail> ReceiptDetails { get; set; } = new List<ReceiptDetail>();
}


// Each ReceiptDetail is related to one Product
public class ReceiptDetail
{
public int Id { get; set; }
// Other properties ....
public int ProductId { get; set; }
public Product Product { get; set; } = new Product();
}

// A Product can be present in none or many ReceiptDetails !!!
public class Product
{
public int Id { get; set;}
// Other properties ...
public virtual ICollection<ReceiptDetail> ReceiptDetails { get; set; } = new List<ReceiptDetail>();
}

context.Receipt.Include(m => m.ReceiptDetail) returns a list of Receipt, with included ReceiptDetails, but Product within ReceiptDetails is NULL !

Also, context.Receipt.Include(m => m.ReceiptDetal).Include(x => x.Product) does not work, and neither does context.Receipt.Include(m => m.ReceiptDetal.Product) ...

What am I missing ?

Any suggestions or help is appreciated !
Was this page helpful?