如何组合多个C# Lambda表达式(Expression<Func<T,T>>)

6

我有以下函数,实际上是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; }
}

顺便提一下,“Problem”类实现了“IBaseEntity”。
我的目的是在UpdateBulk函数中自动附加ModifiedBy和ModifiedDate到updateFactory中,这样就不必在每次调用UpdateBulk时都进行操作。
我试着在上面的UpdateBulk函数中将解析后的“updateFactory”表达式与“modifiedExpression”合并,但返回以下错误:
“ ‘AndAlso’二进制运算符对类型‘Problem’未定义”
是否可能像这样合并Expression,如果可以,我做错了什么? 如果不行,怎样才能将ModifiedBy =“Test”,ModifiedDate = DateTime.Now合并到updateFactory表达式中?
谢谢,Rod

尝试将 .Where(e => e.ProbId == probId) 更改为 .Where(e=> e.ProbId == null ? (e.ProbId == probId) : false)?有时这个问题是由于返回了空数据引起的。 - MT-FreeHK
嗨,MatrixTai。感谢回复,ProbId在数据库中标记为不可为空。我仍然尝试了你的建议,但仍然遇到相同的错误。Rod - Rod
"AndAlso" 用于 "Expression<Func<T,bool>>",对于 "Expression<Func<T,T>>",您需要定义一个表达式访问器,可以在此处找到:[https://dev59.com/q2kv5IYBdhLWcg3waAJT#10613631]。 - Mrinal Kamboj
1个回答

4
您不能使用AndAlso,因为它是针对BinaryExpression - Expression<Func<T,bool>>的,而在这种情况下,您需要使用表达式访问器,如这里所定义的那样,由Marc Gravell(因此他应该得到所有的荣誉)。我正在使用相同的方法来解决您的问题,假设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; }
}

谢谢你,Mrinal。那正是我一直在寻找的解决方案。Rod - Rod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接