带条件包含的 EF 查询

编程入门 行业动态 更新时间:2024-10-28 20:23:55
本文介绍了带条件包含的 EF 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个表:一个 WorkItem 表和一个 WorkItemNote 表.如何返回一个 WorkItem 和所有符合特定条件的 WorkItemNotes?

I have two tables: a WorkItem table, and a WorkItemNote table. How do I return a WorkItem and all of the WorkItemNotes that meet a certain criteria?

我认为这应该很简单,几乎就像一个有条件的包含",对吧?

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.

假设一个WorkItem有很多WorkItemNotes

你可以这样做:

var intermediary = (from item in ctx.WorkItems from note in item.Notes where note.SomeProp == SomeValue select new {item, note}).AsEnumerable();

这会为每个匹配的 WorkItemNote 生成一个匿名元素,并保存相应的 WorkItem.

This produces an anonymous element for each WorkItemNote that matches, and holds the corresponding WorkItem too.

EF 标识解析确保相同的 WorkItem(通过引用)在具有多个符合条件的 WorkItemNotes 时被多次返回.

EF identity resolution insures that the same WorkItem (by reference) is returned multiple times if it has multiple WorkItemNotes that match the criteria.

我假设接下来您只想回到 WorkItems,如下所示:

I assume that next you want to just get back to just the WorkItems, like this:

var workItems = intermediary.Select(x => x.item).Distinct().ToList();

如果你现在这样做:

foreach(var workItem in workItems) { Console.WriteLine(workItem.Notes.Count) }

您将看到与原始过滤器匹配的 WorkItemNotes 已添加到每个 workItem 的 Notes 集合中.

You will see that WorkItemNotes that match the original filter have been added to the Notes collection of each workItem.

这是因为关系修复.

即这给了你你想要的条件包含.

I.e. this gives you what you want conditional include.

希望能帮到你

亚历克斯

更多推荐

带条件包含的 EF 查询

本文发布于:2023-11-15 09:26:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!