如何在 LINQ 中执行嵌套一对多连接

问题描述 投票:0回答:1

如果这很愚蠢,我深表歉意,但在这种情况下如何返回包含 Product 的 IEnumerable

// 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)
返回
Receipt
的列表,其中包含
ReceiptDetails
,但
Product
内的
ReceiptDetails
为NULL!

此外,

context.Receipt.Include(m => m.ReceiptDetal).Include(x => x.Product)
不起作用,
context.Receipt.Include(m => m.ReceiptDetal.Product)
也不起作用...

我错过了什么?

如有任何建议或帮助,我们将不胜感激!

c# entity-framework linq-to-entities
1个回答
0
投票

下面的代码可能适合您。

context.Product.Include(p => p.Receipt).ThenInclude(r => r.ReceiptDetail)
© www.soinside.com 2019 - 2024. All rights reserved.