动态“WHERE IN”关于 IQueryable(linq to SQL)
我有一个 LINQ to SQL 查询,将表中的行返回到 IQueryable 对象中。
IQueryable<MyClass> items = from table in DBContext.MyTable
select new MyClass
{
ID = table.ID,
Col1 = table.Col1,
Col2 = table.Col2
}
然后我想对结果执行 SQL“WHERE ... IN ....”查询。使用以下内容可以很好地工作。 (返回带有 id 的 ID1 ID2 或 ID3 的结果)
sQuery = "ID1,ID2,ID3";
string[] aSearch = sQuery.Split(',');
items = items.Where(i => aSearch.Contains(i.ID));
我希望能够做的是执行相同的操作,但不必指定 i.ID 部分。因此,如果我有要应用“WHERE IN”子句的字段名称字符串,如何在 .Contains() 方法中使用它?
I have a LINQ to SQL query returning rows from a table into an IQueryable object.
IQueryable<MyClass> items = from table in DBContext.MyTable
select new MyClass
{
ID = table.ID,
Col1 = table.Col1,
Col2 = table.Col2
}
I then want to perform a SQL "WHERE ... IN ...." query on the results. This works fine using the following. (return results with id's ID1 ID2 or ID3)
sQuery = "ID1,ID2,ID3";
string[] aSearch = sQuery.Split(',');
items = items.Where(i => aSearch.Contains(i.ID));
What I would like to be able to do, is perform the same operation, but not have to specify the i.ID part. So if I have the string of the field name I want to apply the "WHERE IN" clause to, how can I use this in the .Contains() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种方法可以做到这一点。一种方法是使用 动态 Linq。另一种方法是使用 谓词生成器。
There's a couple of ways to do this. One way is to use Dynamic Linq. Another way is to use Predicate Builder.
你必须构建一个表达式树。它最终看起来像这样(部分代码,无法编译)。这个既包含又等于。在此项目中使用:http://weblogs.asp.net/rajbk/archive/2010/04/15/asp-net-mvc-paging-sorting-filtering-a-list-using-modelmetadata.aspx
我可能会将其重写为可重用的扩展方法(目前它对于该项目来说太具体)并在博客中介绍它。
Your have to build an expression tree. It will end up looking like this (partial code, will not compile). This one does both contains and equals. Used in this project: http://weblogs.asp.net/rajbk/archive/2010/04/15/asp-net-mvc-paging-sorting-filtering-a-list-using-modelmetadata.aspx
I may rewrite this into a reusable extension method (it is too specific to that project at the moment) and blog about it.