/// <summary> /// Updates an existing entry in the context /// </summary> /// <param name="id">The id of the entry to be update, must match the id on the model</param> /// <param name="model">The model with updated data</param> /// <returns>A response model containing any validation results with previous and current versions of the model if successfully updated</returns> public async Task <RepositoryActionResultModel <TModel> > Update(Guid id, TModel model) { // Could add some validation to see if the user is allowed to create this type of entity // as part of a rule based system...? // Validate the Id supplied against that of the model, bit of a crude check but could prevent some simple tampering if (id != model.Id) { return(new RepositoryActionResultModel <TModel> { ResultType = ResultTypeEnum.FailedVerification, PreviousVersion = model }); } // Validate the incoming model against the registered validator var validationResult = await _validator.ValidateUpdate(model); // Return a new result model if validation has failed if (!validationResult.IsValid) { return(new RepositoryActionResultModel <TModel> { PreviousVersion = model, ResultType = ResultTypeEnum.FailedValidation, ValidationResult = validationResult }); } // Now we load the current entity version var currentEntity = await _context.GetEntity <TEntity>(id); // Check to see if the entity was found within the context if (currentEntity == null) { // If not, return a not found message return(new RepositoryActionResultModel <TModel> { ResultType = ResultTypeEnum.NotFound }); } // Create a representation as it is today var currentModel = _mapper.CreateModel(currentEntity); // Update the current entity with the new values passed in _mapper.UpdateEntity(model, currentEntity); // Assign the defaults for updated flags currentEntity.DateUpdated = DateTime.UtcNow; currentEntity.UpdatedByUserId = _authenticatedUser.UserId; // Save to the db, this could be done in a // unit of work pattern and saved later await _context.SaveChangesAsync(); // Create a result containing old and new version, and return return(new RepositoryActionResultModel <TModel> { ResultType = ResultTypeEnum.Success, PreviousVersion = currentModel, CurrentVersion = _mapper.CreateModel(currentEntity) }); }