There is a table called UserFriends
that holds records for users' friendships.
For each friendship, there is just one record,
User1ID User2ID IsConfirmed
1 2 true
which is equal in terms of business logic to
User1ID User2ID IsConfirmed
2 1 true
but both can't happen for one pair.
What is the most efficient (yet readable and not involving plain SQL) Entity Framework query to determine if user A is a friend of user B, considering we don't know which of them is in first or second column?
My attempt is plain and obvious:
public bool AreFriends (int user1Id, int user2Id)
{
return MyObjectContext.UserFriends
.Any (uf => uf.IsConfirmed && (
(uf.UserID == user1Id && uf.FriendUserID == user2Id)
|| (uf.UserID == user2Id && uf.FriendUserID == user1Id)
));
}
Is there a better way than ||
here?
Because an open connection to the database consumes a valuable resource, the Entity Framework opens and closes the database connection only as needed. You can also explicitly open the connection. For more information, see Managing Connections and Transactions. Once in each application domain.
I think if the User1ID and User2ID columns both are primary key columns this query cause an index seek and is so efficient. Tuning of a query when it is critical, without analysing the execution plan, is inefficient. For important queries, I suggest you use SQL Server (or any DBMS) to write and analyse your queries and then convert these queries to LINQ queries. It is not hard.
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