从Expression <func <t,t =“”>&gt; </func <t,>生成动态UPDATE命令

时间:2012-03-16 15:50:01

标签: c# sql linq linq-to-entities expression-trees

我尝试根据表达式树生成UPDATE命令(用于批量更新)。

假设以下UPDATE命令:

UPDATE Product
SET ProductTypeId = 123,
ProcessAttempts = ProcessAttempts + 1

对于这样的表达式:

Expression<Func<Product, Product>> updateExpression = entity =>
    new Product() {
        ProductTypeId = 123,
        ProcessAttempts = entity.ProcessAttempts + 1
    };

如何生成命令的SET部分?

SET ProductTypeId = 123,
ProcessAttempts = ProcessAttempts + 1

1 个答案:

答案 0 :(得分:2)

这是一种非常简单的方法,但我希望它足够好:

private static string ConvertToSetCommand<T>(Expression<Func<T, T>> exp)
{
    if (exp.Body.NodeType != ExpressionType.MemberInit)
    {
        throw new ArgumentException("The expression must have an object initializer.", "exp");
    }

    var builder = new StringBuilder("SET ", 100);
    exp = (Expression<Func<T, T>>) new OmitParametersVisitor().Visit(exp);

    var memberInit = (MemberInitExpression) exp.Body;
    foreach (var assignment in memberInit.Bindings)
    {
        builder.Append(assignment.ToString());
        builder.Append(", ");
    }
    builder.Length -= 2; // Remove the last comma

    return builder.ToString();
}

private class OmitParametersVisitor : ExpressionVisitor
{
    protected override Expression VisitMember(MemberExpression node)
    {
        if (node.Expression != null && node.Expression.NodeType == ExpressionType.Parameter)
        {
            return Expression.Parameter(node.Type, node.Member.Name);
        }
        else
        {
            return base.VisitMember(node);
        }
    }
}