将元组与Entity Framework Contains语句一起使用 [英] Use tuples with Entity Framework Contains statement

查看:82
本文介绍了将元组与Entity Framework Contains语句一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体,其引用是标识符和环境的组合。我想实现一个允许用户传递(ID,Environment)元组列表并返回所需实体的功能。在这种情况下可以使用Contains()吗?怎么样?通过简单的引用,它就像

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))

编辑:澄清一下,我不是在寻找使用Contains()方法检索ID列表;我上面写的那行就是这样做的。我正在寻找的是能够检索与(ID,Environment)的元组匹配的实体列表,而不仅仅是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.

推荐答案

最新版本的Entity Framework允许您对原始类型数组进行包含(我认为它适用于 IEnumerable 现在,我也没有尝试过。)

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).

如果仅在 Id 上进行匹配(也就是说,如果Tuple的ID之一是 MyEntity.Id ,那么您的匹配就很好,这将起作用(我正在使用 Tuple 在这里很不幸,因为您的情况似乎是一个实际的对象; 元组仅具有 ItemN 属性):

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));

这将有效地转换为SQL中的 WHERE ... IN([[containedIds中的ID]] 语句。

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

这篇关于将元组与Entity Framework Contains语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆