不能是你如何做一个SQL风格的“IN”在LINQ声明实体(实体框架)是否包含支持? [英] How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported?
问题描述
我使用LINQ到实体(不是LINQ到SQL),我遇到了麻烦创建IN风格的查询。这是我的时刻查询:
VAR项目= db.InventoryItem
.INCLUDE(类)
.INCLUDE(PropertyValues)
.INCLUDE(PropertyValues.KindProperty)
。凡(ITM = GT; valueIds.Contains(itm.ID))了ToList< InventoryItem>() ;
当我这样做但是,下面抛出异常:
LINQ到实体无法识别方法'布尔包含(Int64的)的方法,而这种方法不能被翻译成店的表情。
< /块引用>
有没有人有一种变通方法或该另一个解决方案?
解决方案您需要为使用这一个:
。凡(的String.Format(it.ID在{0},串。加入(,,valueIds.ToArray())));
或动态构造WHERE部分,为的这个职位。
P.S。 - 信息已经更新,这个答案更新如下,以保持相关性:
引用的链接包含以下更新:
的 ...在EF4我们增加了对的
支持的包含方法至少在本的
的具体案例集合值的
的参数。因此,这种的
的代码现在工作的权利开箱的
的的,这是不是necesary使用任何的
的 additinal表达建筑方法:的
块引用>
VAR statusesToFind =新的List< INT> {1,2,3,4};
变种FOOS从foo =在myEntities.Foos
,其中statusesToFind.Contains(foo.Status)
选择foo的;
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 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?
解决方案You need to either use this one:
.Where(string.Format("it.ID in {0}", string.Join(",", valueIds.ToArray())));
or construct the WHERE part dynamically, as in this post.
P.S. - Information has been updated and this answer updated as follows to maintain relevance:
The link referenced contains the following update:
...in EF4 we added support for the Contains method and at least in this specific case for collection-valued parameters. Therefore this kind of code now works right out of the box and it is not necesary to use any additinal expression building method:
var statusesToFind = new List<int> {1, 2, 3, 4}; var foos = from foo in myEntities.Foos where statusesToFind.Contains(foo.Status) select foo;
这篇关于不能是你如何做一个SQL风格的“IN”在LINQ声明实体(实体框架)是否包含支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!