如何组合多个c#Lambda表达式(Expression <func <t,t =“” >>)

时间:2018-08-23 01:33:44

标签: c# linq expression entity-framework-plus

我有以下功能,它实际上是Z.EntityFramework.Plus批量更新的包装:

    public static int UpdateBulk<T>(this IQueryable<T> query, Expression<Func<T, T>> updateFactory) where T : IBaseEntity, new()
    {
        Expression<Func<T, T>> modifiedExpression = x => new T() { ModifiedBy = "Test", ModifiedDate = DateTime.Now };
        var combine = Expression.Lambda<Func<T, T>>(
            Expression.AndAlso(
                Expression.Invoke(updateFactory, updateFactory.Parameters),
                Expression.Invoke(modifiedExpression, modifiedExpression.Parameters)
            ),
            updateFactory.Parameters.Concat(modifiedExpression.Parameters)
        );  //This returns an error

        return query.Update(combine);
    }

这样称呼:

        decimal probId = ProbId.ParseDecimal();

        db.Problems
            .Where(e => e.ProbId == probId)
            .UpdateBulk(e => new Problem() {
                CatId = Category.ParseNullableInt(),
                SubCatId = SubCategory.ParseNullableInt(),
                ListId = Problem.ParseNullableInt()
            });

IBaseEntity的定义如下:

public abstract class IBaseEntity
{
    public System.DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }

    public System.DateTime ModifiedDate { get; set; }
    public string ModifiedBy { get; set; }

    public string DeletedBy { get; set; }
}

“问题”类通过实现IBaseEntity的方式。

我想做的是在UpdateBulk函数中自动将ModifiedBy和ModifiedDate附加到updateFactory,这样就不必在每次调用UpdateBulk时都这样做。

我在上面的UpdateBulk函数中尝试将解析的'updateFactory'表达式与'modifiedExpression'组合在一起,但是它返回错误:

  
    

未为类型'Problem'定义二进制运算符AndAlso

  

是否可以像这样合并Expression,如果这样做,我在做什么错? 如果没有,如何将ModifiedBy =“ Test”,ModifiedDate = DateTime.Now合并到updateFactory表达式中?

谢谢, 杆

1 个答案:

答案 0 :(得分:2)

您不能使用AndAlso,因为这是BinaryExpression - Expression<Func<T,bool>>的意思,在这种情况下,您需要Expression here定义为Marc Gravell的Expression Visitor(因此,他应得到所有信用)

在假设Problem class schema的情况下,我正在使用相同的方法为您提供解决方案,并粘贴了Linqpad代码:

void Main()
{
  var final = UpdateBulk((Problem p) => new Problem{CatId = 1,SubCatId = 2, ListId=3});

 // final is of type Expression<Func<T,T>>, which can be used for further processing

  final.Dump();
}

public static Expression<Func<T, T>> UpdateBulk<T>(Expression<Func<T, T>> updateFactory) where T : IBaseEntity, new()
{
    Expression<Func<T, T>> modifiedExpression = x => new T() { ModifiedBy = "Test", ModifiedDate = DateTime.Now };

    var result = Combine(updateFactory, modifiedExpression);

    return result;
}


static Expression<Func<TSource, TDestination>> Combine<TSource, TDestination>(
    params Expression<Func<TSource, TDestination>>[] selectors)
{
    var param = Expression.Parameter(typeof(TSource), "x");
    return Expression.Lambda<Func<TSource, TDestination>>(
        Expression.MemberInit(
            Expression.New(typeof(TDestination).GetConstructor(Type.EmptyTypes)),
            from selector in selectors
            let replace = new ParameterReplaceVisitor(
                  selector.Parameters[0], param)
            from binding in ((MemberInitExpression)selector.Body).Bindings
                  .OfType<MemberAssignment>()
            select Expression.Bind(binding.Member,
                  replace.VisitAndConvert(binding.Expression, "Combine")))
        , param);
}

class ParameterReplaceVisitor : ExpressionVisitor
{
    private readonly ParameterExpression from, to;
    public ParameterReplaceVisitor(ParameterExpression from, ParameterExpression to)
    {
        this.from = from;
        this.to = to;
    }
    protected override Expression VisitParameter(ParameterExpression node)
    {
        return node == from ? to : base.VisitParameter(node);
    }
}

public abstract class IBaseEntity
{
    public System.DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }

    public System.DateTime ModifiedDate { get; set; }
    public string ModifiedBy { get; set; }

    public string DeletedBy { get; set; }
}

public class Problem : IBaseEntity
{
    public int CatId { get; set; }

    public int SubCatId { get; set; }

    public int ListId { get; set; }
}