System.Linq.Dynamic - 可以在WHERE语句中使用IN子句 [英] System.Linq.Dynamic - Can I use IN clause in WHERE statement
问题描述
我有动态的linq WHERE语句:
I have dynamic linq WHERE statement:
dataContext.Table.Where("id = 0 Or id = 1 Or id = 2 Or ...");
我想更改为:
dataContext.Table.Where("id IN (0, 1, 2, ...)");
但它没有工作。如何才能做到更好的表现?
But it doesn´t work. How can I do this for better performance?
推荐答案
//edit: this is probably broken, see below
ids = new int[] {1,2,3,4};
dataContext.Table.Where("id.Contains(@0)", ids);
Aside:在动态linq表达式中使用占位符是个好习惯。否则你可能会打开自己进行linq注入攻击(是否可以通过动态LINQ注入?)
Aside: It is good practice to use placeholders in dynamic linq expressions. Otherwise you may open yourself to linq injection attacks (Is Injection Possible through Dynamic LINQ?)
编辑:
其实我觉得我搞砸了。
不幸的是我现在无法测试。
但是我认为在这种情况下正确的语法应该是 dataContext.Table.Where(@ 0.Contains(id),ids);
,而不是其他方式,而该版本不可以开箱即用。
actually I think I messed this up.
Unfortunately I cannot test this at the moment.
But I think the correct syntax in this case should be dataContext.Table.Where("@0.Contains(id)",ids);
, not the other way around, and that version does not work out-of-the-box.
请参阅这里的一种方法来添加这个功能到动态链接。您需要修改这个库。
See here for a way to add this functionality to dynamic link. You need to modify the library for this.
这篇关于System.Linq.Dynamic - 可以在WHERE语句中使用IN子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!