如何在linq中包含()嵌套子实体 [英] How to include() nested child entity in linq
问题描述
我应如何包含一个拥有儿童身份的孩子?
How do I include a child of a child entitiy?
即,乔布斯的报价中包含QuoteItems
Ie, Jobs have Quotes which have QuoteItems
var job = db.Jobs
.Where(x => x.JobID == id)
.Include(x => x.Quotes)
.Include(x => x.Quotes.QuoteItems) // This doesn't work
.SingleOrDefault();
请更清楚一点-我正在尝试检索单个Job项目,它是相关的Quotes(一对多),对于每个Quote,它都是相关的QuoteItems(一个Quote可以有多个QuoteItems)
Just to be clearer - I'm trying to retrieve a single Job item, and it's associated Quotes (one to many) and for each Quote the associated QuoteItems (One Quote can have many QuoteItems)
我问的原因是因为在我的报价索引"视图中,我试图通过对小计求和来显示每个报价的所有报价项的总计,但它的值为0.我称小计像这样:
The reason I'm asking is because in my Quote Index view I'm trying to show the Total of all the Quote items for each Quote by SUMming the Subtotal, but it's coming out as 0. I'm calling the Subtotal like this:
@item.QuoteItem.Sum(p => p.Subtotal)
我相信我遇到此问题的原因是,我上面的Linq查询没有检索每个Quote的关联QuoteItems.
I believe the reason I have this issue is that my Linq query above isn't retrieving the associated QuoteItems for each Quote.
推荐答案
要获得一份工作并渴望加载其所有报价及其报价单,请编写:
To get a job and eager load all its quotes and their quoteitems, you write:
var job = db.Jobs
.Include(x => x.Quotes.Select(q => q.QuoteItems))
.Where(x => x.JobID == id)
.SingleOrDefault();
如果QuoteItems也是一个集合,则可能需要SelectMany
而不是Select
.
You might need SelectMany
instead of Select
if QuoteItems is a collection too.
给他人的注释;强类型Include()
方法是扩展方法,因此您需要在文件顶部添加using System.Data.Entity;
.
Note to others; The strongly typed Include()
method is an extension method so you need to include using System.Data.Entity;
at the top of your file.
这篇关于如何在linq中包含()嵌套子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!