chenk chenk - 1 month ago 7
C# Question

LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[Entities.Connection])' method

I tried to create list of notes that satisfying either of two conditions.
1. Matched with the created user.
2. OR Linked with the connections.

using the below code returns an exception.

"LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[Entities.Connection])' method, and this method cannot be translated into a store expression."

_context.Notes
.Include(t => t.Connections)
.Where(t => t.CreatedUserId == userId || t.Connections.ToList().Exists(c => c.UserId == userId))

Answer

The issue here is that Entity Framework does not understand your C# code and cannot parse .Exists().

An alternative way of writing this would be as followed:

_context.Notes
    .Include(t => t.Connections)
    .Where(t => t.CreatedUserId == userId || t.Connections.Any(c => c.UserId == userId));

Here the .Any() will return true if any Connections have a UserId that is equal to userId.

Comments