2

I have a table named Items. Items have a property named "locationId" Given a list of location Ids, how do I select all items?

List example

List<long> locationIds = new List<long> { 1, 2, 3 };

Essentially the query below, but for multiple locations at once:

var sleectedItems= db.Items.Select(i => i.LocationId == 2);
VSO
  • 11,546
  • 25
  • 99
  • 187

1 Answers1

6

You need to use Where with Contains:

var selectedItems = db.Items.Where(x => locationIds.Contains(x.LocationId));
haim770
  • 48,394
  • 7
  • 105
  • 133
  • Thanks for the answer, any idea what I am doing wrong? http://i.imgur.com/VY1RkK8.png – VSO Jun 15 '15 at 06:57
  • What is the type of `LocationId`? – haim770 Jun 15 '15 at 06:59
  • It's "long" in entity, big int in the db. – VSO Jun 15 '15 at 07:02
  • The error message implies that it's not `long`. Maybe it's `long?` (`Nullable`)? – haim770 Jun 15 '15 at 07:05
  • That was my understanding of the error as well. It's a long though: " [DatabaseGenerated(DatabaseGeneratedOption.None)] public virtual long Id { get; set; }" - this is from the model definition. I will come back and accept your answer once I figure it out. I am sure it SHOULD work, I just don't know why it doesn't for me. – VSO Jun 15 '15 at 07:08
  • 1
    You showed the property definition of `Id`, we're talking about `LocationId`. – haim770 Jun 15 '15 at 07:40
  • You were right - it was long?. Sorry, I was working 12+ hours straight at that point, so I was a bit out of it. Thank you very, very much. – VSO Jun 15 '15 at 12:13