1

I have an entity whose reference is a composite of an identifier and an environment. I want to implement a function to allow the user to pass a list of tuples of (ID, Environment) and return back the required entities. Is it possible to use Contains() in such scenarios? How? With a simple reference, it is as simple as

model.MyEntities.Where(e => myIds.Contains(e.Id))

EDIT: To clarify, I am not looking for how to use Contains() method to retrieve a list of IDs; the line I wrote above does this. What I am looking for is to be able to retrieve a list of entities matching tuples of (ID, Environment) rather than just ID.

Rafid
  • 18,991
  • 23
  • 72
  • 108
  • 1
    http://stackoverflow.com/questions/6912733/linq-to-entities-where-in-clause-with-multiple-columns - I'd say your best bet is to `Union()` the queries for the IDs together and hope the SQL optimizer can make sense of that. – millimoose Jul 11 '13 at 14:18
  • 1
    Another option would be using LinqKit to dynamically build a chain of `OR`s. – millimoose Jul 11 '13 at 14:22

1 Answers1

1

Latest version of Entity Framework allows you to do a Contains on an array of primitive types (I think it works on an IEnumerable too now, I haven't tried).

If you match solely on your Id (ie, your match is good if one of the Tuple's ID is the MyEntity.Id, this will work (I'm using Tuple losely here as your case seems to be an actual object; Tuple only has ItemN properties):

var containedIds = yourListOfTuples.Select(t => t.Id).ToArray();
model.MyEntities.Where(e => containedIds.Contains(e.Id));

This will effectively translate into a WHERE ... IN ([the Ids in containedIds]) statement in SQL.

Simon Belanger
  • 14,752
  • 3
  • 41
  • 35
  • 1
    Just to expand on that, it's important to convert the tuples to a normal array, because EF cannot convert a tuple to SQL inherently. – Erik Funkenbusch Jul 11 '13 at 14:01
  • @MystereMan Correct. I specified `array of primitive types` but I should have been more explicit. – Simon Belanger Jul 11 '13 at 14:02
  • That doesn't really answer the question. I already actually mentioned above how to use Contains() for IDs. My problem is whether Entity Framework supports using Contains() with composite keys, e.g. myTuples.Contains(new {Id, Environment}). – Rafid Jul 11 '13 at 14:10
  • @Rafid Last time I investigated this, the answer seemed to be "nope, not as far as anyone else can see". – millimoose Jul 11 '13 at 14:14
  • @Rafid Contains will work on primitive types only, unfortunately. – Simon Belanger Jul 11 '13 at 14:14