将元组与Entity Framework Contains语句一起使用

编程入门 行业动态 更新时间:2024-10-27 18:23:28
本文介绍了将元组与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语句一起使用

本文发布于:2023-11-14 16:20:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   将元组   Entity   Framework

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!