Reputation: 592
I have a query that select all Photos if its public, and only if friends if visibility is private in this code.
_communityDbContext
.Photos
.Where(x => (
x.Privacy == 1 ||
(x.Privacy == 2 &&
_communityDbContext.Friendships.FirstOrDefault(d => x.CreatedBy.Id == user1 && d.FriendUser.Id == user2) !=
null)
)
);
But I trying to extract this piece of code to reuse in another queries
_communityDbContext.Friendships.FirstOrDefault(d => x.CreatedBy.Id == user1 && d.FriendUser.Id == user2) != null
Is possible to call an function and make the code like that:
_communityDbContext
.Photos
.Where(x => (
x.Privacy == 1 ||
(x.Privacy == 2 &&
hasFriendship(x.CreatedBy.Id, user))
)
);
Upvotes: 2
Views: 1566
Reputation: 592
I fond a solution, the method invocation must be done to an expression, not to a function call. So I can extract that part of code by doing
public Expression<Func<Photo, bool>> Visible()
{
return x => (
x.Privacy == 1 ||
(x.Privacy == 2 &&
_communityDbContext.Friendships.FirstOrDefault(d => x.CreatedBy.Id == 3 && d.FriendUser.Id == 3) !=
null)
);
}
And calling this by
.where(Visible())
Upvotes: 2