0

I am going to use github.com/loresoft/EntityFramework.Extended library to batch update. Here is the sample code to use for batch update:

context
.Tasks
.Where(t => t.StatusId == 1)
.Update(t => new Task { StatusId = 2 }) 

I want to specify StatusId or other propery like Discontinued, UnitsInStock which is specified by user.

How can i achieve this by passing property as string and build dynamic expression.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136

1 Answers1

0

As long as the updates are to static values (ie, not reference other variables), you can use the following method:

public static Expression<Func<T,T>> CreateNewObjectExpression<T>(Dictionary<string, object> props) {
    // set props
    var type = typeof(T);
    // This is the `new T` part of the expression
    var newExpr = Expression.New(type);
    // Convert the values to set to expressions
    var members = from prop in props
                  let val = Expression.Constant(prop.Value)
                  select new KeyValuePair<string, Expression>(prop.Key, val);
    // this is the full new T { prop1 = val1 ... }
    var initExpr = BindMembers(newExpr, members);

    // And now we add the parameter part `t => `
    return Expression.Lambda<Func<T, T>>(initExpr, Expression.Parameter(typeof(T)));
}

static MemberInitExpression BindMembers(NewExpression expr, IEnumerable<KeyValuePair<string, Expression>> assignments) {
    Type type = expr.Type;
    List<MemberBinding> bindings = new List<MemberBinding>();
    foreach (var pair in assignments) {
        MethodInfo info = type.GetProperty(pair.Key).GetSetMethod();
        MemberBinding binding = Expression.Bind(info, pair.Value);
        bindings.Add(binding);
    }
    return Expression.MemberInit(expr, bindings);
}

These methods can be used like this:

var props = new Dictionary<string,object>();
// get the properties from the user instead, of course
props["StatusId"] = 2;
// Now get the expression:
var updateExpr = CreateNewObjectExpression<Task>(props);
// and apply it
context.Tasks.Where(t => t.StatusId == 1)
    .Update(updateExpr);

Be careful of only setting properties that are present and writable in the target class, otherwise you'll get a crash.

felipe
  • 662
  • 4
  • 16