问题描述
根据需求,我们需要编写如下的SQL语句来查询产品
select * from dbo.Product
where
(ProductName like 'Product1%' or
ProductName like 'Product2%')
如何将以上的SQL语句转换成EF的写法呢?
方案一
可以使用Union,将以上SQL语句转换成以下的形式:
select * from dbo.Product
where
ProductName like 'Product1%'
UNION
select * from DocutapCMS.dbo.Product
where
ProductName like 'Product2%'
然后将上路SQL换成Linq To EF就非常简单了,再此就不贴出来了。但每个条件都要写一个Query,工作量大。如果条件太多,生成的SQL语句也非常大,并且写起来很费力。
方案二
我们从Linq To EF的Contains功能得到启发,Linq To EF 会将Contains转换成IN表达式。
那么我们可不可以直接写Expression,将条件转换成上述SQL语句呢?答案是肯定的。以下就是实现上述方案的具体Linq To EF扩展。
public static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector,
IEnumerable<TValue> values)
{
var startsWithMethod = typeof (string).GetMethod("StartsWith", new[] { typeof(string) });
var startWiths = values.Select(value => (Expression)Expression.Call(valueSelector.Body, startsWithMethod, Expression.Constant(value, typeof(TValue))));
var body = startWiths.Aggregate<Expression>(((accumulate, equal) => Expression.Or(accumulate, equal)));
var p = Expression.Parameter(typeof(TElement));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
用法:
private static void QueryProducts(IQueryable<Product> query)
{
var productNames = new string[] {"P1", "P2"};
var query1 = from a in query.Where(BuildContainsExpression<Product, string>(d=>d.ProductName, productNames))
select a;
var items2 = query1.ToList();
}
private static void QueryProducts(IQueryable<Product> query)
{
var productNames = new string[] {"P1", "P2"};
var query1 = from a in query.Where(BuildContainsExpression<Product, string>(d=>d.ProductName, productNames))
select a;
var items2 = query1.ToList();
}
创建扩展方法,让调用变得简单
public static IQueryable<TElement> WhereOrLike<TElement, TValue>(this IQueryable<TElement> query,
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
return query.Where(BuildContainsExpression<TElement, TValue>(valueSelector, values));
}
private static void QueryProducts2(IQueryable<Product> query)
{
var productNames = new string[] {"P1", "P2"};
query.WhereOrLike(d=>d.ProductName, productNames).ToList();
}
通过SQL Profile 监视生成的SQL语句
-- Region Parameters
DECLARE @p0 NVarChar(3) = 'P1%'
DECLARE @p1 NVarChar(3) = 'P2%'
-- EndRegion
SELECT [t0].[Id], [t0].[ProductName]
FROM [Product] AS [t0]
WHERE ([t0].[ProductName] LIKE @p0) OR ([t0].[ProductName] LIKE @p1)