[英]EF get specific related objects
I have a collection of objects in my EF repository called Territories
. 我的EF储存库中有一个名为Territories
的对象集合。 A Territory
is linked to many Distributions
, and each Distribution
has one CycleID
. 一个Territory
链接到许多Distributions
,每个Distribution
都有一个CycleID
。
How would I write a query against EF that will grab all the Territory
objects and the associated Distributions
that belong to a specific Cycle
, ignoring any Territories
that do not have any qualifying Distributions
? 我将如何针对EF编写查询,该查询将获取属于特定Cycle
所有Territory
对象和关联的Distributions
,而忽略没有任何合格Distributions
所有Territories
?
I'm picturing something like: 我在想像这样的东西:
return this.entities.Territories
.Include("Distributions")
.Include("Reps")
.Where(e => e.Distributions.Any(d => d.CycleID == CycleID))
.OrderBy(e => e.TerritoryName)
.AsEnumerable();
but I'm collecting bad Distributions
. 但是我正在收集不良的Distributions
。 I can see what it's doing, but I can't figure out how to make it do what I want. 我可以看到它在做什么,但是我不知道如何使它按我的意愿去做。
It seems like you are choosing the wrong entry point to your object graph. 似乎您为对象图选择了错误的入口点。 Start with what you know (the specific Cycle
) and work back to the items you want to retrieve (the Distributions
and Territories
). 从您知道的内容(特定的Cycle
)开始,然后回到要检索的项目(“ Distributions
和Territories
)。
var cycle = this.entities.Cycles.Single(c => c.CycleID == cycleID);
return cycle.Include("Distributions")
.Include("Territories")
.Include("Territories.Reps");
Depending on how you're using the result, you may want to transform it to Enumerable<Territory>
根据您使用结果的方式,您可能需要将其转换为Enumerable<Territory>
return cycle.Distributions.SelectMany(d => d.Territories)
.OrderBy(t => t.TerritoryName)
.AsEnumerable();
You may have to play around with the Include
statements because my EF is a bit rusty. 您可能必须使用Include
语句,因为我的EF有点生锈。
Try this : 尝试这个 :
var entities = new TestEntities();
var cycleId = 1;
var filteredDistributions = entities.Territories
.Join(entities.Distributions.Where(d => d.CycleId == cycleId),
territory => territory.Id,
distribution => distribution.Territory.Id,
(territory, distribution) => distribution);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.