Using Entity Framework Core 2.2 I have the following queries:
dbContext.Projects.Where(x => x.Jobs.All(y => y.UserId != userId))
dbContext.Projects.Where(x => !x.Jobs.Any(y => y.UserId == userId))
So I am getting all projects which does not have any Job where Job.UserId equals userId.
I believe both do the same but which one is fastest?
These are fully equivalent, thus should have one and the same performance in any normal query provider implementation.
Speaking about EF Core, both are translated to one and the same SQL using
NOT EXISTS (subquery)
criteria, so the performance of executing the SQL query is one and the same. Of course since SQL has not special construct forAll
(SQLEXISTS
== LINQAny
), the translation ofAll
should be slightly slower than translation ofAny
(basically has to convert it to the negated version ofAny
), but negligible compared with the time of executing and materializing the query.So in general use the one which gives you better readability. I personally prefer
Any
because it naturally maps to SQL, thus has bigger chance to be supported by the query provider. But since EF Core supports both, it's really a matter of taste.