public async Task <RepositoryOperationResult> AddAsync(T itemToAdd) { RepositoryOperationResult result = null; if (itemToAdd != null) { try { var itemProperties = itemToAdd.GetType().GetProperties(); var tableName = GetTableName(itemToAdd); var sqlCommandStringBuilder = new StringBuilder($"INSERT INTO {tableName}"); AppendColumnNames(sqlCommandStringBuilder, itemProperties); sqlCommandStringBuilder.Append(" VALUES"); AppendColumnValues(sqlCommandStringBuilder, itemProperties, itemToAdd); sqlCommandStringBuilder.Append(';'); await using var sqlConnection = new SqlConnection(_dbConnectionString); await sqlConnection.OpenAsync(); var sqlInsertCommand = new SqlCommand(sqlCommandStringBuilder.ToString(), sqlConnection); await sqlInsertCommand.ExecuteNonQueryAsync(); result = new RepositoryOperationResult(true); } catch (Exception e) { result = new RepositoryOperationResult(false, new List <string>() { e.Message }); } } else { result = new RepositoryOperationResult(false, new List <string>() { "Parameter can not be null" }); } return(result); }
public async Task <RepositoryOperationResult> DeleteAsync(T itemToDelete) { RepositoryOperationResult result; try { _dbSet.Remove(itemToDelete); await _context.SaveChangesAsync(); result = new RepositoryOperationResult(true); } catch (Exception ex) { _logger.Error(ex, $"An error occured when deleting {nameof(itemToDelete)} entity"); result = new RepositoryOperationResult(false, new List <string>() { ex.Message }); } return(result); }
public async Task <RepositoryOperationResult> UpdateAsync(T itemToUpdate) { RepositoryOperationResult result; try { var state = GetState(itemToUpdate); if (state == EntityState.Detached) { var existingAttachedEntity = _dbSet.Local.FirstOrDefault(e => e.Id == itemToUpdate.Id); if (existingAttachedEntity != null) { var attachedEntry = _context.Entry(existingAttachedEntity); attachedEntry.CurrentValues.SetValues(itemToUpdate); } } else { _dbSet.Attach(itemToUpdate); SetEntityStateModified(itemToUpdate); } await _context.SaveChangesAsync(); result = new RepositoryOperationResult(true); } catch (Exception ex) { _logger.Error(ex, $"An error occured when updating {nameof(itemToUpdate)} entity"); result = new RepositoryOperationResult(false, new List <string>() { ex.Message }); } return(result); }