我必须编写一个在LinqToSQL中使用的过滤lambda表达式,它需要的不仅仅是标准System.Func提供的参数数量(在这种情况下,最大数量是16)。
Expression<Func<BusinessDTO,
string,
int,
int,
int,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
int,
int,
int,
int,//-> Max number exceeded
bool>> fnFilter = (business,
Name,
Redeemed,
Permanent,
ApprovedByUser,
BeginApprovalDate,
EndApprovalDate,
BeginExpiryDate,
EndExpiryDate,
BeginEntryDate,
EndEntryDate,
BeginChangeDate,
EndChangeDate,
WorkFlowCode,
CreatedByUser,
UpdatedByUser) => ...
我怎样才能做到这一点?
以下是用法:
filterExpression = Expression.Invoke(fnFilter, businessParam,
Expression.Constant(name),
Expression.Constant(redeemed),
Expression.Constant(permanent),
Expression.Constant(approvedByUser),
Expression.Constant(filter.BeginApprovalDate),
Expression.Constant(filter.EndApprovalDate),
Expression.Constant(filter.BeginExpiryDate),
Expression.Constant(filter.EndExpiryDate),
Expression.Constant(filter.BeginEntryDate),
Expression.Constant(filter.EndEntryDate),
Expression.Constant(filter.BeginChangeDate),
Expression.Constant(filter.EndChangeDate),
Expression.Constant(workflowCode),
Expression.Constant(createdByUser),
Expression.Constant(updatedByUser));
var resultExpression = Expression.Equal(filterExpression, Expression.Constant(true));
var predicate = Expression.Lambda<Func<BusinessDTO, bool>>(resultExpression, businessParam);
repository.FindAll(predicate);
答案 0 :(得分:1)
我们的产品在.NET 3.5天内遇到此限制,当时限制为4.我们最终将额外参数分组到一个对象中,为此我们创建了一个具有32个类型参数的怪异泛型类型:
class FilterParams<T1,T2,T3,T4,/*..*/,T32> {
public T1 t1Val {get;set;}
public T2 t1Val {get;set;}
public T3 t1Val {get;set;}
// ...
}
Expression<Func<BusinessDTO,FilterParams<
string,
int,
int,
int,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
DateTime,
int,
int,
int,
int,//-> Max number is not exceeded :)
bool,object,object,/* pad to 32 ...*/>> fnFilter = (business,
filterParams) => business.Name.Equals(filterParams.t0val) && ...
var fp = new FilterParams</*ugly type parameter list*/>(
t0val = name,
t1val = redeemed,
t2val = permanent,
// ...and so on
);
filterExpression = Expression.Invoke(fnFilter, businessParam, Expression.Constant(fp));
// ...the rest is the same as in your post
这对我们来说非常有效。最后我们将它扩展到64,并创建了64个不同的类,以避免使用object
填充类型参数,如上所示。当然,我们编写了一个小脚本来生成这64个泛型类。