加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ to SQL:注意一个预构建的表达式

发布时间:2020-12-15 17:49:03 所属栏目:百科 来源:网络整理
导读:我正在为我的一个核心L2S类建立一个函数库,所有这些函数都返回一个bool来允许检查某些情况. 例: ExpressionFuncAccount,bool IsSomethingX = a = a.AccountSupplementary != null a.AccountSupplementary.SomethingXFlag != null a.AccountSupplementary.So
我正在为我的一个核心L2S类建立一个函数库,所有这些函数都返回一个bool来允许检查某些情况.

例:

Expression<Func<Account,bool>> IsSomethingX =
      a => a.AccountSupplementary != null
         && a.AccountSupplementary.SomethingXFlag != null
         && a.AccountSupplementary.SomethingXFlag.Value;

现在查询哪里不正确,我不能这样做:

var myAccounts= context.Accounts
      .Where(!IsSomethingX); // does not compile

但是,使用PredicateBuilder类的语法,我已经提出:

public static IQueryable<T> WhereNot<T>(this IQueryable<T> items,Expression<Func<T,bool>> expr1)
{
    var invokedExpr = Expression.Invoke(expr1,expr1.Parameters.Cast<Expression>());
    return items.Where(Expression.Lambda<Func<T,bool>>
          (Expression.Not(invokedExpr),expr1.Parameters));
}

var myAccounts= context.Accounts
      .WhereNot(IsSomethingX); // does compile

这实际上产生了正确的SQL.

这看起来像一个很好的解决方案,有什么我需要知道的,可能会导致我的问题在未来?

解决方法

我使用WhereNot扩展方法编写了一些测试代码,它看起来不错. @ Stephan的解决方案也是有效的,但是我可以考虑扩展方法的可读性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读