问题
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.
回答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.
来源:https://stackoverflow.com/questions/17595105/use-tuples-with-entity-framework-contains-statement