public static async Task UpdateAsync <T>(this DbContext context, IQueryable <T> query, PropertyWatcher <T> Saved) where T : class, new() { //var itemParam = Expression.Parameter(typeof(T), "x"); //var primaryKeys = Utilities.GetPrimaryKeys(typeof(T), context); //var primaryKeyArgs = primaryKeys.Select(c => Expression.PropertyOrField(itemParam, c.Name)).ToArray(); //var selector = Expression.Call(typeof(Tuple), "Create", primaryKeyArgs.Select(c => c.Type).ToArray(), primaryKeyArgs); //var lambda = Expression.Lambda<Func<T, object>>(selector, itemParam); //foreach (var item in query.Select(lambda.Compile())) //{ // T ret = new T(); // foreach (var v in primaryKeys.Select((c, index) => new { c, index })) // { // var tupleProp = item.GetType().GetProperty("Item" + v.index).GetValue(item); // v.c.SetValue(ret, tupleProp); // } // var updated = context.Entry(ret); // Saved.LoadToInstance(ref ret); // foreach (var v in Saved.GetValues()) // { // updated.Property(v.Key.Name).IsModified = true; // } //} await query.ForEachAsync(item => { var ret = item; var updated = context.Entry(ret); Saved.LoadToInstance(ref ret); foreach (var v in Saved.GetValues()) { updated.Property(v.Key.Name).IsModified = true; } }); context.Configuration.ValidateOnSaveEnabled = false; }
public static void Update <T, T2>(this DbContext context, PropertyWatcher <T> Saved, Expression <Func <T, T2> > KeyField, T2 KeyValue) where T : class, new() { var ret = new T(); Saved.LoadToInstance(ref ret); var prop = Reflection.GetPropertyInfo(KeyField); prop.SetValue(ret, KeyValue); context.Set <T>().Attach(ret); var updated = context.Entry <T>(ret); foreach (var v in Saved.GetValues()) { updated.Property(v.Key.Name).IsModified = true; } context.Configuration.ValidateOnSaveEnabled = false; }