C#成员表达式Func <t,object>到Func <t,bool> MethodBinaryExpression

时间:2015-12-03 13:11:21

标签: c# lambda expression servicestack

是否可以将成员epxression与对象一起转换为c#中的方法二进制表达式?

到目前为止我尝试了什么:

public static void SaveBy<T>(this IDbConnection db, T obj, Expression<Func<T, object>> exp) where T : new()
{
    var com  = exp.Compile();
    if (db.Update(obj, e => exp == com.Invoke(obj)) <= 0)
    {
        db.Insert(obj);
    }
}

public static void UpdateBy<T>(this IDbConnection db, T obj, Expression<Func<T, bool>> exp) where T : new()
{
    db.Update(obj, exp);
}

我想要实现的是制作一个可以用

调用的方法
x.SaveBy(object,model=>model.property)

将调用x.Update,将MemberExpression转换为methodBinaryExpression,如下所示:

x.Update(object, model=>model.property == object.property);

中途解决方案

public static void SaveBy<T>(this IDbConnection db, T obj, Expression<Func<T, object>> exp) where T : new()
    {
        var result = exp.Compile().Invoke(obj);
        var exp2 = Expression.Lambda<Func<T, bool>>(Expression.Equal(exp.Body, Expression.Constant(result)), exp.Parameters);
        if (db.Update(obj, exp2) <= 0)
        {
            db.Insert(obj);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以创建新表达式

model=>model.property == object.property

public static void SaveBy<T, TProp>(this IDbConnection db, T obj, Expression<Func<T, TProp>> exp) where T : new()
{
    var memberExp = (MemberExpression)exp.Body;
    var objPropExp = Expression.PropertyOrField(Expression.Constant(obj), memberExp.Member.Name);
    var equalExp = Expression.Equal(exp.Body, objPropExp);
    var exp2 = Expression.Lambda<Func<T, bool>>(equalExp, exp.Parameters);
    //exp2 = {model => (model.prop == value(object).prop)}

    if (db.Update(obj, exp2) <= 0)
    {
        db.Insert(obj);
    }
}