实体框架,如何使用 LinQ 手动生成实体的内部联接
假设我有一个名为 Foo 的表,其中包含主键 FooID 和整数非唯一列 Bar。由于某种原因,在 SQL 查询中,我必须多次将表 Foo 与其自身连接起来,如下所示:
SELECT * FROM Foo f1 INNER JOIN Foo f2 ON f2.Bar = f1.Bar INNER JOIN Foo f3 ON f3.Bar = f1.Bar...
我必须通过 LINQ to Entities 来实现此目的。
执行
ObjectContext.Foos.Join(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b})
给出我在结果查询中使用了 LEFT OUTER JOIN,并且我需要内部联接,这是非常关键的。
当然,如果在 edmx 中我根据需要添加了尽可能多的 Foo 与其自身的关联,然后在我的代码中使用它们,我可能会成功,实体框架将为每个关联替换正确的内部联接。问题是在设计时我不知道需要多少个连接。好的,一种解决方法是添加尽可能多的合理...
但是,如果没有别的办法,从理论的角度来看,是否可以在不显式定义关联的情况下通过 EF 创建内部联接?
在 LINQ to SQL 中,有一种(有点奇怪)通过 GroupJoin 执行此操作的方法,如下所示:
ObjectContext.Foos.GroupJoin(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b}).SelectMany(o = > obDefaultIfEmpty(), (o, b) => new {oa, b)
我刚刚在 EF 中尝试过,该技巧在那里不起作用。它仍然为我生成外部连接。
有什么想法吗?
Let's imagine I have an table called Foo with a primary key FooID and an integer non-unique column Bar. For some reason in a SQL query I have to join table Foo with itself multiple times, like this:
SELECT * FROM Foo f1 INNER JOIN Foo f2 ON f2.Bar = f1.Bar INNER JOIN Foo f3 ON f3.Bar = f1.Bar...
I have to achieve this via LINQ to Entities.
Doing
ObjectContext.Foos.Join(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b})
gives me LEFT OUTER JOIN in the resulting query and I need inner joins, this is very critical.
Of course, I might succeed if in edmx I added as many associations of Foo with itself as necessary and then used them in my code, Entity Framework would substitute correct inner join for each of the associations. The problem is that at design time I don't know how many joins I will need. OK, one workaround is to add as many of them as reasonable...
But, if nothing else, from theoretical point of view, is it at all possible to create inner joins via EF without explicitly defining the associations?
In LINQ to SQL there was a (somewhat bizarre) way to do this via GroupJoin, like this:
ObjectContext.Foos.GroupJoin(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b}).SelectMany(o = > o.b.DefaultIfEmpty(), (o, b) => new {o.a, b)
I've just tried it in EF, the trick does not work there. It still generates outer joins for me.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Linq to Entities 中,以下是对同一表的多个实例执行内部联接的一种方法:
In Linq to Entities, below is one way to do an inner join on mutiple instances of the same table: