如果不支持Contains,您如何在LINQ to Entities(Entity Framework)中执行SQL风格的“IN”语句? [英] How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported?
问题描述
我正在使用LINQ to Entities(而不是LINQ to SQL),并且我无法创建IN样式的查询。这是我现在的查询:
I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query. Here is my query at the moment:
var items = db.InventoryItem
.Include("Kind")
.Include("PropertyValues")
.Include("PropertyValues.KindProperty")
.Where(itm => valueIds.Contains(itm.ID)).ToList<InventoryItem>();
当我这样做,抛出以下异常:
When I do this however, the following exception is thrown:
LINQ to Entities不会识别方法Boolean Contains(Int64)方法,并且此方法无法转换为存储表达式。
LINQ to Entities does not recognize the method 'Boolean Contains(Int64)' method, and this method cannot be translated into a store expression.
有没有人有解决方法或其他解决方案?
Does anyone have a workaround or another solution for this?
推荐答案
你需要使用这个:
.Where(string.Format("it.ID in {0}", string.Join(",", valueIds.ToArray())));
或动态构建WHERE部分,如这个的帖子。
or construct the WHERE part dynamically, as in this post.
引用的链接包含以下更新:
The link referenced contains the following update:
...在EF4中,我们添加了对
的支持包含方法,至少在这个
具体案例,用于收集价值
参数。因此,这种
代码现在可以开箱即用,
,并不需要使用任何
附加表达式构建方法
var statusesToFind = new List<int> {1, 2, 3, 4};
var foos = from foo in myEntities.Foos
where statusesToFind.Contains(foo.Status)
select foo;
这篇关于如果不支持Contains,您如何在LINQ to Entities(Entity Framework)中执行SQL风格的“IN”语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!