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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With