Use tuples with Entity Framework Contains statement

江枫思渺然 提交于 2020-01-14 04:09:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!