1,构造表达式树

也说Linq动态条件查询    private Expression<Func<Blog, bool>> getCondition()
    }
主查询是这个样子:
也说Linq动态条件查询        var result = new DongBlogDataContext().Blogs.Where(getCondition());
也说Linq动态条件查询
因为根据SQL追踪,生成SQL类似:
也说Linq动态条件查询SELECT [t0].[BlogID][t0].[ChannelID][t0].[BlogClassID][t0].[Title][t0].[Content][t0].[Tag][t0].[CreateDateTime]
也说Linq动态条件查询
FROM [dbo].[Blog] AS [t0]
也说Linq动态条件查询
WHERE [t0].[BlogClassID] IS NULL

这种方法是实质是合并Lamba表达式,也就是这三句:

也说Linq动态条件查询                Expression<Func<Blog, bool>> e = blog => blog.BlogClass == null;
也说Linq动态条件查询                var invokedExpr 
= Expression.Invoke(e, expression.Parameters.Cast<Expression>());
也说Linq动态条件查询
也说Linq动态条件查询                expression 
= Expression.Lambda<Func<Blog, bool>>(Expression.And(expression.Body, invokedExpr), expression.Parameters);
也说Linq动态条件查询

如果每个条件合并都这么写会很麻烦,幸好已经有人给写好的辅助类:http://www.albahari.com/expressions/

也说Linq动态条件查询using System;
也说Linq动态条件查询
using System.Linq;
也说Linq动态条件查询
using System.Linq.Expressions;
也说Linq动态条件查询
using System.Collections.Generic;
也说Linq动态条件查询 
也说Linq动态条件查询
public static class PredicateBuilder

这个类可以用于Expression<Func<T, bool>>类型的表达式的合并了。具体用法参看http://www.albahari.com/expressions/http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1745163&SiteID=1

2,构造Query
同第一种查询更好的写法:

也说Linq动态条件查询    private IQueryable<Blog> getQuery()
    }

主查询

也说Linq动态条件查询var result = getQuery();

生成的SQL和第一个完全相同。

园子里相关讨论还有
http://www.cnblogs.com/neuhawk/archive/2007/07/07/809585.html
http://www.cnblogs.com/blusehuang/archive/2007/07/13/816970.html
还可参考:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1706161&SiteID=1

相关文章: