2

我希望在到数据库的单次往返中执行以下两个查询,所以我使用 ToFutureValue。

var query = AsQueryable()
    .Where(x => x.User == user);

var singinCount = query
    .Where(x => x.ActionDate >= from && x.ActionDate <= to)
    .ToFutureValue(q => q.Count());

var lastSignin = query
    .Where(x => x.ActionName.ToLower() == Actions.Signin))
    .ToFutureValue(q => q.Max(x => x.ActionDate));

问题是 Count 和 Max 返回结果而不是 IQueryable。我找到了以下扩展,使我能够将 Count 传递给 ToFutureValue:

public static IFutureValue<TResult> ToFutureValue<TSource, TResult>(
    this IQueryable<TSource> source, Expression<Func<IQueryable<TSource>, TResult>> selector)
        where TResult : struct
    {
        var provider = (INhQueryProvider)source.Provider;
        var method = ((MethodCallExpression)selector.Body).Method;
        var expression = Expression.Call((Expression)null, method, source.Expression);

        return (IFutureValue<TResult>)provider.ExecuteFuture(expression);
    }

现在我需要为 Max 采用该扩展,因为我必须将参数传递给 Max (.ToFutureValue(q => q.Max(x => x.ActionDate)))。我怎样才能做到这一点?

4

2 回答 2

0

作为一种解决方法

var lastSignin = query
    .Where(x => x.ActionName.ToLower() == Actions.Signin))
    .OrderByDescending(x => x.ActionDate)
    .Take(1)
    .ToFutureValue();
于 2012-07-05T14:35:09.750 回答
0

看起来 GitHub pull request #120中有适当的补丁

这是jira bug NH-3184

以下是来自 pull #120 的有效代码:

public static IFutureValue<TResult> ToFutureValue<T, TResult>(
    this IQueryable<T> query, Expression<Func<IQueryable<T>, TResult>> selector)
{
    var nhQueryable = query as QueryableBase<T>;    
    if (nhQueryable == null)
    {
        throw new NotSupportedException("Query needs to be of type QueryableBase<T>");
    }


    var provider = (INhQueryProvider) query.Provider;
    var expression = ReplacingExpressionTreeVisitor.Replace(
            selector.Parameters.Single(),
            query.Expression,
            selector.Body);

    return (IFutureValue<TResult>) provider.ExecuteFuture(expression);
}
于 2012-07-31T05:28:54.240 回答