开发者

Entity Framework, how to manually produce inner joins with LinQ to entitites

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) =&g开发者_JAVA百科t; 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?


In Linq to Entities, below is one way to do an inner join on mutiple instances of the same table:

using (ObjectContext ctx = new ObjectContext())
{

    var result = from f1 in ctx.Foo
                 join f2 in ctx.Foo on f1.bar equals f2.bar
                 join f3 in ctx.Foo on f1.bar equals f3.bar
                 select ....;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜