首页 新闻 赞助 找找看

如果创建Lambda表达式参数的函数

0
悬赏园豆:10 [已解决问题] 解决于 2016-03-21 15:59

我想实现的功能有点像entity framework的where函数,我通过where函数传入一个Lambda表达式,然后通过这个表达式来生成对应的SQL语句,请大神指教!!

Eoin的主页 Eoin | 初学一级 | 园豆:195
提问于:2013-06-11 11:11
< >
分享
最佳答案
0
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.OrElse (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.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

这个是PredicateBuilder的代码。你可以采用这个结合LinqKit来实现EF的动态条件。

如何使用?

var where=PredicateBuilder.True<T>();

where=where.Where(m=>m.id=1);

 

 

收获园豆:10
幻天芒 | 高人七级 |园豆:37175 | 2013-06-11 19:06
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册