代码之家  ›  专栏  ›  技术社区  ›  Apeiron

SQL Server未计算表达式

  •  2
  • Apeiron  · 技术社区  · 7 年前

        public static Func<TSource, bool> WhereNotNullClause<TSource>(string propertyName)
        {
            var type = typeof(TSource);
            var expression = Expression.Parameter(type, "p");
            var propertyNameReference = Expression.Property(expression, propertyName);
            var propertyValueReference = Expression.Constant(null);
    
            return Expression.Lambda<Func<TSource, bool>>(
                Expression.NotEqual(propertyNameReference, propertyValueReference),
                new[] { expression }).Compile();
        }
    

    var whereNotNullSelector = Expressions.WhereNotNullClause<ContactItem>("property");
    var contactItems = context.ContactItems.Where(whereNotNullSelector).ToList();
    

    生成的SQL不包括where子句,因此where似乎是在查询解析后执行的。 在我能够正确解决这个问题之前,我还需要处理哪些事情?

    1 回复  |  直到 7 年前
        1
  •  3
  •   DavidG    7 年前

    您的方法返回一个 Func Expression Enumerable.Where 而不是 Queryable.Where .Compile :

    public static Expression<Func<TSource, bool>> WhereNotNullClause<TSource>(string propertyName)
    {
        var type = typeof(TSource);
        var expression = Expression.Parameter(type, "p");
        var propertyNameReference = Expression.Property(expression, propertyName);
        var propertyValueReference = Expression.Constant(null);
    
        return Expression.Lambda<Func<TSource, bool>>(
            Expression.NotEqual(propertyNameReference, propertyValueReference),
            new[] { expression });
    }
    

    一些额外的阅读 here 关于为什么你 而不是 Func公司 。将表达式视为数据而不是实际的委托,这意味着Linq to SQL可以将表达式树转换为SQL,而Func本质上是一个黑匣子。