Entity Framework List Contains in lambda
12,169
- Will this generate a single query with SQL IN operator?
Yes - Is this code OK in terms of performance?
Yes (for small lists) - Are there any better ways to do it?
No (for small lists)
If the list is really big and the table is reasonably small you might get better performance bringing the complete table into memory and do an in memory join with the list.
Author by
Andrei
There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors. .NET, Azure, ASP.NET MVC, JavaScript, React-Native
Updated on July 20, 2022Comments
-
Andrei almost 2 years
I want to query items with specific IDs using. For example:
var ids = new List<int> { 1, 3, 5 }; var items = context.Items.Where(item => ids.Contains(item.ID)).ToList();
Questions:
- Will this generate a single query with SQL
IN
operator? - Is this code OK in terms of performance?
- Are there any better ways to do it?
I am using Entity Framework 6 with Microsoft SQL Server.
- Will this generate a single query with SQL
-
Giorgi over 8 yearsSQL IN will be generated only if the provider supports it. Sql Server providers supports it but Oracle provider doesn't
-
Douglas Gaskell almost 7 yearsFor me this brings the entire table in, then grabs the values it needs from memory. Considering the table has ~15 million rows, this is crippling performance wise. It pretty much performs a
SELECT * FROM
query without anIN
. -
Magnus almost 7 years@DouglasGaskell Perhaps you are using an older version of EF. Or using non SQL-Server provider.
-
Douglas Gaskell almost 7 years@Magnus I'm using EF Core (7) right now. I may be missing this sort of functionality.
-
yv989c over 2 yearsHi @DouglasGaskell. If you are using EF Core 3.1+, you may find my work useful: github.com/yv989c/BlazarTech.QueryableValues