转:动态LINQ的几种方法
来自:http://www.yaosansi.com/post/1382.html
在使用LINQ中,会发现使用很多传统的多条件查询很难实现。
这里提供网上已有的几种方法:
一、用表达式树依据 IQueryable 数据源构造一个动态查询
参见:博客园 李永京http://www.cnblogs.com/lyj/archive/2008/03/25/1122157.html
二、使用LINQ动态查询库(Scott提供)
允许你使用接受字符串参数(而不是类安全的语言运算符)的扩展方法来表示LINQ查询。
中文原文:http://blog.joycode.com/scottgu/archive/2008/01/09/113554.aspx
下载:
- Basic Dynamic LINQ C# Sample
- Basic Dynamic LINQ VB Sample
dynamic-linq使用强类型举例:
Dynamic LINQ中的时间比较:
" and insertTime.value.CompareTo('" + StartDate.Value + "')>=0 and insertTime.value.CompareTo( '" + Convert.ToDateTime(EndDate.Value).AddDays(1).ToString() + "')<=0"
或者
" and insertTime>=" + DateTime.Parse(StartDate.Value)+ "
Dynamic LINQ中的LIKE:
.Where("AdminName.Contains('a')");
生成的SQL语句
SELECT * FROM [dbo].[Admin] AS [t0]
WHERE [t0].[AdminName] LIKE @p0
-- @p0: Input VarChar (Size = 3; Prec = 0; Scale = 0) [%a%]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1
三、Using PredicateBuilder(Dynamically Composing Expression Predicates)
-
原文:http://www.albahari.com/nutshell/predicatebuilder.aspx
使用前:
IQueryable<Product> SearchProducts (params string[] keywords)
{
IQueryable<Product> query = dataContext.Products;
foreach (string keyword in keywords)
{
string temp = keyword;
query = query.Where (p => p.Description.Contains (temp));
}
return query;
}
使用后:Using PredicateBuilderIQueryable<Product> SearchProducts (params string[] keywords)
{
var predicate = PredicateBuilder.False<Product>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
return dataContext.Products.Where (predicate);
}
PredicateBuilder 源码:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T> () { return f => true; }
public static Expression<Func<T, bool>> False<T> () { return f => false; }
public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.Or (expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.And (expr1.Body, invokedExpr), expr1.Parameters);
}
}