[英]EF Query With Conditional Include
I have two tables: a WorkItem table, and a WorkItemNote table. 我有两个表:一个WorkItem表和一个WorkItemNote表。 How do I return a WorkItem and all of the WorkItemNotes that meet a certain criteria?
如何返回符合特定条件的WorkItem和所有WorkItemNotes?
I think this should be simple, almost like a conditional "Include", right? 我认为这应该很简单,几乎就像有条件的“包含”一样,对吧?
I've been planning on writing a tip on this but your question beat me to the punch. 我一直在计划写一个关于这个的小费 ,但是你的问题让我很震惊。
Assuming a WorkItem
has many WorkItemNotes
假设
WorkItem
有许多WorkItemNotes
you can do this: 你可以这样做:
var intermediary = (from item in ctx.WorkItems
from note in item.Notes
where note.SomeProp == SomeValue
select new {item, note}).AsEnumerable();
This produces an anonymous element for each WorkItemNote
that matches, and holds the corresponding WorkItem
too. 这会为每个匹配的
WorkItemNote
生成一个匿名元素,并保存相应的WorkItem
。
EF identity resolution insures that the same WorkItem
(by reference) is returned multiple times if it has multiple WorkItemNotes
that match the criteria. EF标识解析确保如果具有与条件匹配的多个
WorkItemNotes
,则多次返回相同的WorkItem
(通过引用)。
I assume that next you want to just get back to just the WorkItems
, like this: 我假设接下来你只想回到
WorkItems
,就像这样:
var workItems = intermediary.Select(x => x.item).Distinct().ToList();
Then if you now do this: 那么如果你现在这样做:
foreach(var workItem in workItems)
{
Console.WriteLine(workItem.Notes.Count)
}
You will see that WorkItemNotes
that match the original filter have been added to the Notes collection of each workItem
. 您将看到与原始过滤器匹配的
WorkItemNotes
已添加到每个workItem
的Notes集合中。
This is because of something called Relationship Fixup. 这是因为称为关系修复的东西。
Ie this gives you what you want conditional include. 也就是说,这给了你想要条件的东西。
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.