我希望在数据库的单次往返中执行以下两个查询,因此我使用的是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 =&gt; q.Max(x =&gt; x.ActionDate)))。我怎么能这样做?
答案 0 :(得分:0)
作为解决方法
var lastSignin = query
.Where(x => x.ActionName.ToLower() == Actions.Signin))
.OrderByDescending(x => x.ActionDate)
.Take(1)
.ToFutureValue();
答案 1 :(得分:0)
看起来在GitHub拉取请求中有适当的补丁 #120
这是jira bug NH-3184
以下是拉#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);
}