Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - join with OR condition

I've got two entities, Users and Friendships which look like:

    public class User
    {
        public int UserId { get; set; }
        (...)
    }

    public class Friendship
    {
         public int SenderId { get; set; }
         public int ReceiverId { get; set; }
         (...)
    }

And I would like to create simple query which in SQL would look like:

    SELECT * FROM Users as U
    INNER JOIN Friendships as F ON U.UserId = F.ReceiverId OR U.UserId = F.SenderId
    Where U.Nick != VARIABLE

In other words I would like to select all friends of the user.

And I can't accomplish that. I've found solution where one creates two separate join queries with union and it works - but it's not efficient to create such query to db.

like image 848
Nevararn Avatar asked Sep 26 '12 21:09

Nevararn


People also ask

Can we use joins in Linq?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.

What type of join is Linq join?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source.

Is Linq join inner or outer?

One commonly used feature of Language-Integrated Query (LINQ) is the facility to combine two sequences of related data using joins. The standard join operation provides an inner join but with a minor modification can be changed to give a left outer join.


1 Answers

Joins in LINQ are always equijoins. Basically you need multiple from clauses and a where clause:

var query = from u in db.Users
            where u.Nick != variable
            from f in db.Friendships
            where u.UserId == f.ReceiveId || u.UserId == f.SenderId
            select ...;

Now in LINQ to Objects there are probably more efficient ways of doing this - but I'd expect a SQL-based LINQ provider to generate a query which has a good enough execution plan. It may not actually create a JOIN in the SQL, but I'd expect it to be the same execution plan as the join you've shown.

like image 94
Jon Skeet Avatar answered Oct 09 '22 05:10

Jon Skeet