如果我想要检索更多具有已存在的lambda树表达式的列
如下,我该怎么做?这适用于实体框架,并希望它仍然有效.
Expression<Func<DivisionTeam, DirectorTeamModel>> columns= (d) => new DirectorTeamModel
{
Id = d.Id,
TeamId = d.Team.Id
};
if (criteria.Template == ExportTemplate.Import || criteria.Template == ExportTemplate.Default)
{
// Retrieve additional columns from "columns" expression tree
}
return _divisionTeamsRepository.GetPagedResults(criteria.Page, criteria.PageSize, @where.Expand(), string.Format("{0} {1}", criteria.SortOrder, criteria.SortDirection), columns);
最佳答案 给定两个“selector”表达式,您将从其MemberInitExpression中获取绑定并使用所有绑定创建一个新表达式.但是这个表达式不起作用,因为它为一个参数使用两个不同的参数表达式.我们也需要解决这个问题.
鉴于…
Expression<Func<TSource, TResult>> left = ... // columns
Expression<Func<TSource, TResult>> right = ... // more columns
……拿绑定……
var leftInit = left.Body as MemberInitExpression;
var rightInit = right.Body as MemberInitExpression;
var bindings = leftInit.Bindings.Concat(rightInit.Bindings);
……创造一个新的表达……
var result = Expression.Lambda<Func<TSource, TResult>>(
Expression.MemberInit(Expression.New(typeof(TResult)), bindings), ???);
…但是,需要单个参数……
var binder = new ParameterBinder(left.Parameters[0], right.Parameters[0]);
var bindings = binder.Visit(leftInit.Bindings.Concat(rightInit.Bindings));
// now, just use right.Parameters[0] as parameter...
并且,使用表达式访问者更换参数效果很好:
class ParameterBinder : ExpressionVisitor
{
readonly ParameterExpression parameter;
readonly Expression replacement;
public ParameterBinder(ParameterExpression parameter, Expression replacement)
{
this.parameter = parameter;
this.replacement = replacement;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node == parameter)
return replacement;
return base.VisitParameter(node);
}
}
抽象这个管道的东西工作得很好.事实上,你可以使用existing library(剧透:我是作者),这应该导致类似的东西:
var merged = columns.Apply(moreColumns);