private ResponseBase InitializeUpdate(UpdateRangeCommand command, KeyValuePair <Type, string> property, HttpInformation context, SapphireDbContext db) { object[] updateValues = command.UpdateValues.Values <JObject>().Select(newValue => newValue.ToObject(property.Key)).ToArray(); UpdateRangeResponse response = new UpdateRangeResponse { ReferenceId = command.ReferenceId, Results = updateValues.Select(updateValue => { if (!property.Key.CanUpdate(context, updateValue, serviceProvider)) { return(command.CreateExceptionResponse <UpdateResponse>( "The user is not authorized for this action.")); } object[] primaryKeys = property.Key.GetPrimaryKeyValues(db, updateValue); object value = db.Find(property.Key, primaryKeys); if (value != null) { db.Entry(value).State = EntityState.Detached; return(ApplyChangesToDb(property, value, updateValue, db, context)); } return(command.CreateExceptionResponse <UpdateResponse>("No value to update was found")); }).ToList() }; db.SaveChanges(); foreach (object value in updateValues) { property.Key.ExecuteHookMethods <UpdateEventAttribute>(ModelStoreEventAttributeBase.EventType.After, value, context, serviceProvider); } return(response); }
private async Task <ResponseBase> InitializeUpdate(UpdateRangeCommand command, KeyValuePair <Type, string> property, HttpInformation context, SapphireDbContext db) { List <object> updateValues = command.Entries.Select(e => e.Value) .Select(newValue => newValue.ToObject(property.Key)) .ToList(); UpdateRangeResponse response; bool updateRejected; do { updateRejected = false; response = new UpdateRangeResponse { ReferenceId = command.ReferenceId, Results = updateValues.Select((updateValue, index) => { if (!property.Key.CanUpdate(context, updateValue, serviceProvider)) { return((UpdateResponse)command.CreateExceptionResponse <UpdateResponse>( "The user is not authorized for this action.")); } object[] primaryKeys = property.Key.GetPrimaryKeyValues(db, updateValue); object value = db.Find(property.Key, primaryKeys); if (value != null) { object previousValue = command.Entries[index].Previous?.ToObject(property.Key); return(ApplyChangesToDb(property, value, updateValue, previousValue, db, context)); } return((ValidatedResponseBase)CreateRangeCommandHandler .SetPropertiesAndValidate <UpdateEventAttribute>(db, property, updateValue, context, serviceProvider)); }).ToList() }; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { foreach (EntityEntry entityEntry in db.ChangeTracker.Entries()) { await entityEntry.ReloadAsync(); } updateRejected = true; } } while (updateRejected); foreach (object value in updateValues) { property.Key.ExecuteHookMethods <UpdateEventAttribute>(ModelStoreEventAttributeBase.EventType.After, value, context, serviceProvider); } return(response); }