C# 如何在实体框架中进行“in”查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1137921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:07:34  来源:igfitidea点击:

How to do an "in" query in entity framework?

c#.netlinqentity-framework

提问by NotDan

How can I do a select in linq to entities to select rows with keys from a list? Something like this:

如何在 linq 中选择实体以从列表中选择带有键的行?像这样的东西:

var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders 
              where (order.Key in orderKeys) 
              select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);

I tried using the Containsmethod as mentioned in some of the answers but it does not work and throws this exception:

我尝试使用某些答案中提到的Contains方法,但它不起作用并引发此异常:

LINQ to Entities does not recognize the method 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' method, and this method cannot be translated into a store expression.

LINQ to Entities 无法识别方法 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' 方法,并且此方法无法转换为存储表达式。

采纳答案by Andrew Hare

Try this:

尝试这个:

var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders 
              where orderKeys.Contains(order.Key);
              select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);

Edit:I have found some workarounds for this issue - please see WHERE IN clause?:

编辑:我找到了一些解决此问题的方法 - 请参阅WHERE IN 子句?

The Entity Framework does not currently support collection-valued parameters ('statusesToFind' in your example). To work around this restriction, you can manually construct an expression given a sequence of values using the following utility method:

实体框架目前不支持集合值参数(在您的示例中为“statusesToFind”)。要解决此限制,您可以使用以下实用程序方法手动构造给定值序列的表达式:

回答by Alex James

Unfortunately the EF can't translate the queries others have suggested. So while those queries would work in LINQ to Objects, they won't work in LINQ to Entities.

不幸的是,EF 无法翻译其他人建议的查询。因此,虽然这些查询适用于 LINQ to Objects,但它们不适用于 LINQ to Entities。

So the solution is a little more involved.

所以解决方案有点复杂。

However I have a blog post on this exact topic here. Essentially the solution is to use a little expression tree magic to build an big OR expression.

但是,我在这里有一篇关于这个确切主题的博客文章。本质上,解决方案是使用一点表达式树魔法来构建一个大的 OR 表达式。

Hope this helps

希望这可以帮助

Alex

亚历克斯

回答by eka808

I had the same problem and i solved like this

我有同样的问题,我是这样解决的

var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders 
              where (orderKeys.Contains(order.Key)) 
              select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);