21

I want to convert this SQL query to an Entity Framework Core 2.0 query.

SELECT * FROM Product WHERE ProdID IN (1,2,3); 
8
  • ProdID column is of bigint type and contains only works with string columns Commented Aug 31, 2018 at 7:32
  • 10
    A question about Entity Framework Core 2.0 in 2018 is not a duplicate of a LINQ to Entities question from 2009. Commented Feb 23, 2019 at 13:55
  • @MarkRendle I suppose you're right...however the technique still applies. The underlying IQueryable implementation is what's different between various Linq-to-something technologies...making usage (fairly) consistent across the board. Folks unfamiliar with the history of Linq may not realize this. Commented Feb 23, 2019 at 17:43
  • 1
    @KumudiniPorwal, Contains in Linq is a generic function taking a lambda as an argument...and can be of any type as inferred by the lambda itself. Commented Feb 23, 2019 at 17:46
  • @Clay sure but the linked answer is not what you would do using Marten, or NHibernate, or RavenDB. We shouldn't be linking EF Core to EF or Linq2Sql. Commented Feb 24, 2019 at 7:18

1 Answer 1

35

As per the comments on the question, the way you do this in EF Core is the same as for LINQ-to-SQL: use the Enumerable.Contains extension method on an array in your Where expression.

public async Task<List<Product>> GetProducts(params int[] ids) { return await context.Products .Where(p => ids.Contains(p.ProdID)) // Enumerable.Contains extension method .ToListAsync(); } 

See related LINQ to Entities question

Sign up to request clarification or add additional context in comments.

2 Comments

In my case ProdID is nullable, which means I get a compilation error stating int[] doesn't contain a method Contains that accepts a nullable int. What's the best way to do this in my case? Use p.ProdID.Value?
@JonKoeter Would int?[] work?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.