18

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

SELECT * 
FROM Product
WHERE ProdID IN (1,2,3);
Jeroen
  • 60,696
  • 40
  • 206
  • 339
Kumudini Porwal
  • 181
  • 1
  • 1
  • 5
  • ProdID column is of bigint type and contains only works with string columns – Kumudini Porwal Aug 31 '18 at 07:32
  • 10
    A question about Entity Framework Core 2.0 in 2018 is not a duplicate of a LINQ to Entities question from 2009. – Mark Rendle Feb 23 '19 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. – Clay Feb 23 '19 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. – Clay Feb 23 '19 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. – Phill Feb 24 '19 at 07:18
  • @Clay As you say, the SQL generation code for LINQ-to-Entities is completely different from EF Core's, so there's no reason to assume that the solution is the same. In search-ability terms, it would be better to have an answer to this EF Core question than the "Duplicate" flag. – Mark Rendle Feb 24 '19 at 19:50
  • I voted to reopen, given the collective concern. However, the point of Linq is that the *usage* is supposed to be identical across technologies...and I assume that's how the original duplicate flagger felt. So...to be clear, I'll go ahead and tag it Linq, too ;-) – Clay Feb 24 '19 at 22:00
  • Do you mean this _context.Products.Where(p=>products.Contains(p.ProdID))? or you mean how to use Raw Sql? – Vova Bilyachat Feb 24 '19 at 22:10

1 Answers1

31

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

Mark Rendle
  • 9,274
  • 1
  • 32
  • 58