如何修改Expression <func <???,bool =“”>&gt;?</func <???,>的类型参数

时间:2014-01-16 06:38:00

标签: c# linq entity-framework expression

我有以下实例:

Expression<Func<IRequiredDate, bool>>

我希望将其转换为以下实例,因此可用于在Entity Framework中运行查询:

Expression<Func<TModel, bool>>

这将允许我对任何实现IRequiredDate的模型使用通用过滤查询,例如:

// In some repository function:
var query = DbContext.Set<Order>()
     .FilterByDateRange(DateTime.Today, DateTime.Today);

var query = DbContext.Set<Note>()
     .FilterByDateRange(DateTime.Today, DateTime.Today);

var query = DbContext.Set<Complaint>()
     .FilterByDateRange(DateTime.Today, DateTime.Today);


// The general purpose function, can filter for any model implementing IRequiredDate
public static IQueryable<TModel> FilterByDate<TModel>(IQueryable<TModel> query, DateTime startDate, DateTime endDate) where TModel : IRequiredDate
{
    // This will NOT WORK, as E/F won't accept an expression of type IRequiredDate, even though TModel implements IRequiredDate
    // Expression<Func<IRequiredDate, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
    // query = query.Where(dateRangeFilter);

    // This also WON'T WORK, x.Date is compiled into the expression as a member of IRequiredDate instead of TModel, so E/F knocks it back for the same reason:
    // Expression<Func<TModel, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
    // query = query.Where(dateRangeFilter);

    // All you need is lov.... uh... something like this:
    Expression<Func<IRequiredDate, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
    Expression<Func<TModel, bool>> dateRangeFilterForType = ConvertExpressionType<IRequiredDate, TModel>(dateRangeFilter); // Must convert the expression from one type to another
    query = query.Where(dateRangeFilterForType) // Ahhhh. this will work.

    return query;
}

public static ConvertExpressionType<TInterface, TModel>(Expression<Func<TInterface, bool>> expression)
where TModel : TInterface // It must implement the interface, since we're about to translate them
{
    Expression<Func<TModel, bool>> newExpression = null;

    // TODO: How to convert the contents of expression into newExpression, modifying the
    // generic type parameter along the way??

    return newExpression;
}

我知道他们是不同的类型,不能演员。但是我想知道是否有办法创建新的Expression<Func<TModel, bool>>,然后根据提供的Expression<Func<IRequiredDate, bool>>的内容重建它,将任何类型的引用从IRequiredDate切换到TModel在这个过程中。

可以这样做吗?

3 个答案:

答案 0 :(得分:9)

所以实际进行映射的方法并不是 很难,但遗憾的是,没有一种方法可以让我看到它的推广。这是一个方法,它采用Func<T1, TResult>并将其映射到委托,其中参数的派生比T1更多:

public static Expression<Func<NewParam, TResult>> Foo<NewParam, OldParam, TResult>(
    Expression<Func<OldParam, TResult>> expression)
    where NewParam : OldParam
{
    var param = Expression.Parameter(typeof(NewParam));
    return Expression.Lambda<Func<NewParam, TResult>>(
        expression.Body.Replace(expression.Parameters[0], param)
        , param);
}

这使用Replace方法将一个表达式的所有实例替换为另一个表达式。定义是:

internal class ReplaceVisitor : ExpressionVisitor
{
    private readonly Expression from, to;
    public ReplaceVisitor(Expression from, Expression to)
    {
        this.from = from;
        this.to = to;
    }
    public override Expression Visit(Expression node)
    {
        return node == from ? to : base.Visit(node);
    }
}

public static Expression Replace(this Expression expression,
    Expression searchEx, Expression replaceEx)
{
    return new ReplaceVisitor(searchEx, replaceEx).Visit(expression);
}

现在我们可以使用这个方法(应该给出一个更好的名字),如下所示:

Expression<Func<object, bool>> oldExpression = whatever;
Expression<Func<string, bool>> newExpression =
    Foo<string, object, bool>(oldExpression);

当然,由于Func实际上与其参数协变,我们可以确定对此方法的任何调用都会生成不会添加运行时失败点的表达式。

你可以为Func<T1, T2, TResult>轻松制作此版本,依此类推,直到16种不同类型的Func,如果你愿意,只需为每个类型创建一个参数表达式,然后替换所有有新的那些旧的。这很乏味,但只是遵循这种模式。鉴于旧的和新的参数类型都需要一个泛型参数,并且没有办法推断出参数,那就太麻烦了。

答案 1 :(得分:3)

幸运的是,对于你想要的东西,没有必要使用表达式树。您需要的是增强模板限制:

public static IQueryable<TModel> FilterByDate<TModel>(this IQueryable<TModel> src, DateTime startDate, DateTime endDate) where TModel: class, IRequiredDate {
    return src.Where(x => x.Date >= startDate && x.Date <= endDate);
}

一点解释。使用LINQPad,您可以看到在删除class要求时生成的表达式树是不同的。当出现限制时,Where子句就像这样:

.Where (x => (x => x.Date >= startDate && x.Date <= endDate))

当删除限制时,表达式会发生如下变化:

.Where (x => (x => (((IRequiredDate)x).Date >= startDate) && (((IRequiredDate)x).Date <= endDate)))

表达式树有一些额外的强制转换,这就是为什么在这种形式下,实体框架告诉你它不能用于IRequiredDate类型的实例。

答案 2 :(得分:-1)

我只有几分钟,所以我没有想到这一点。这有帮助吗?

Expression<Func<IList, bool>> exp1 = (list => list.Count > 0);
Expression<Func<string[], bool>> exp2 = (list => exp1.Compile()(list));
Expression<Func<List<int>, bool>> exp3 = (list => exp1.Compile()(list));

我有点展示你想要的东西。

相关问题