我正在尝试基于表达式树生成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
最佳答案 这是一种非常简单的方法,但我希望它足够好:
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);
}
}
}