11

以下 Linq-to-Entities 查询工作正常:

var query = repository.Where(r => r.YearProp1.HasValue &&
                                  r.YearProp1 >= minYear &&
                                  r.YearProp1 <= maxYear);

我的数据库有十几个列,它们都报告与年份相关的信息(short?数据类型)。我想为所有这些列重用相同的 Linq-to-Entities 逻辑。就像是:

Func<RepoEntity, short?> fx = GetYearPropertyFunction();
var query = repository.Where(r => fx(r).HasValue &&
                                  fx(r) >= minYear &&
                                  fx(r) <= maxYear);

这会导致错误:

LINQ to Entities 无法识别方法 'System.Nullable`1[System.Int16] fx(RepoEntity)' 方法,并且此方法无法转换为存储表达式。

我理解为什么我会收到错误,但我想知道是否有一种解决方法不涉及重复代码十几次,只是为了更改 SQL 查询正在运行的属性。

我会在多个查询中重用该函数,所以我想我的问题的一般版本是:有没有办法将一个简单的属性获取器 lambda 函数转换为 Linq-to-Entities 可以使用的表达式?

4

3 回答 3

2

以 Raphaël Althaus 的回答为基础,但添加了您最初寻找的通用选择器:

public static class Examples
{
    public static Expression<Func<MyEntity, short?>> SelectPropertyOne()
    {
        return x => x.PropertyOne;
    }

    public static Expression<Func<MyEntity, short?>> SelectPropertyTwo()
    {
        return x => x.PropertyTwo;
    }

    public static Expression<Func<TEntity, bool>> BetweenNullable<TEntity, TNull>(Expression<Func<TEntity, Nullable<TNull>>> selector, Nullable<TNull> minRange, Nullable<TNull> maxRange) where TNull : struct
    {
        var param = Expression.Parameter(typeof(TEntity), "entity");
        var member = Expression.Invoke(selector, param);

        Expression hasValue = Expression.Property(member, "HasValue");
        Expression greaterThanMinRange = Expression.GreaterThanOrEqual(member,
                                             Expression.Convert(Expression.Constant(minRange), typeof(Nullable<TNull>)));
        Expression lessThanMaxRange = Expression.LessThanOrEqual(member,
                                          Expression.Convert(Expression.Constant(maxRange), typeof(Nullable<TNull>)));

        Expression body = Expression.AndAlso(hasValue,
                      Expression.AndAlso(greaterThanMinRange, lessThanMaxRange));

        return Expression.Lambda<Func<TEntity, bool>>(body, param);
    }
}

可以像您正在寻找的原始查询一样使用:

Expression<Func<MyEntity, short?>> whatToSelect = Examples.SelectPropertyOne;

var query = Context
            .MyEntities
            .Where(Examples.BetweenNullable<MyEntity, short>(whatToSelect, 0, 30));
于 2012-06-18T21:16:39.370 回答
1

谓词本身就是一个过滤器,应该评估为 bool(是否将其包含在结果中)。您可以修改您的方法,使其看起来像这样,它应该可以工作:

public static Expression<Func<RepoEntity, bool>> FitsWithinRange(int minYear, int maxYear)
{
    return w => w.HasValue && w >= minYear && w <= maxYear;
}

编辑:哦,使用它:

var query = repository.Where(Repository.FitsWithinRange(minYear, maxYear));
于 2012-06-18T17:34:59.500 回答
1

你可以做这样的事情(不确定它是否会在 linq2 实体中“按原样”工作,但如果你有问题......告诉)

用法

var query = <your IQueryable<T> entity>.NullableShortBetween(1, 3).ToList();

功能

public static IQueryable<T> NullableShortBetween<T>(this  IQueryable<T> queryable, short? minValue, short? maxValue) where T: class
        {
            //item (= left part of the lambda)
            var parameterExpression = Expression.Parameter(typeof (T), "item");

            //retrieve all nullable short properties of your entity, to change if you have other criterias to get these "year" properties
            var shortProperties = typeof (T).GetProperties().Where(m => m.CanRead && m.CanWrite && m.PropertyType == typeof(short?));

            foreach (var shortProperty in shortProperties)
            {
                //item (right part of the lambda)
                Expression memberExpression = parameterExpression;
                //item.<PropertyName>
                memberExpression = Expression.Property(memberExpression, shortProperty);
                //item.<PropertyName>.HasValue
                Expression firstPart = Expression.Property(memberExpression, "HasValue");
                //item.<PropertyName> >= minValue
                Expression secondPart = Expression.GreaterThanOrEqual(memberExpression, Expression.Convert(Expression.Constant(minValue), typeof (short?)));
                //item.<PropertyName> <= maxValue
                var thirdPart = Expression.LessThanOrEqual(memberExpression, Expression.Convert(Expression.Constant(maxValue), typeof (short?)));
                //item.<PropertyName>.HasValue && item.<PropertyName> >= minValue
                var result = Expression.And(firstPart, secondPart);
                //item.<PropertyName>.HasValue && item.<PropertyName> >= minValue && item.<PropertyName> <= maxValue
                result = Expression.AndAlso(result, thirdPart);
                //pass the predicate to the queryable
                queryable = queryable.Where(Expression.Lambda<Func<T, bool>>(result, new[] {parameterExpression}));
            }
            return queryable;
        }

编辑:另一种解决方案,基于“简单”反射,“看起来”是你想要的

public static short? GetYearValue<T>(this T instance)
        {
            var propertyInfo = typeof(T).GetProperties().FirstOrDefault(m => m.CanRead && m.CanWrite && m.PropertyType == typeof(short?));
            return propertyInfo.GetValue(instance, null) as short?;
        }

用法

var result = list.Where(item => item.GetYearValue() != null && item.GetYearValue() >= 1 && item.GetYearValue() <= 3).ToList();
于 2012-06-18T20:28:24.740 回答