Example #1
0
        /// <summary>
        /// Find an entity and handle null exception.
        /// </summary>
        private T FindEntity <T>(int id) where T : class, IIdentifier
        {
            try
            {
                var entity = _context.Set <T>().AsNoTracking().SingleOrDefault(arg => arg.Id == id);

                if (entity == null)
                {
                    throw new NotFoundException($"Could not find an object with id {id}.");
                }

                return(entity);
            }
            catch (InvalidOperationException ex)
            {
                LoggerExtensions.LogErrorWithInnerExceptions(_logger, ex);
                throw new TooManyFoundException(ex.Message, ex);
            }
        }
Example #2
0
        /// <summary>
        /// Save change, handle exceptions that it might cause and log the event.
        /// </summary>
        protected void SaveChanges <T>(T entity, EventType eventType) where T : class, IIdentifier
        {
            try
            {
                int changes = _context.SaveChanges();

                if (changes == 0)
                {
                    throw new NoChangesException($"No changes in context after SaveChanges when doing {eventType}. Type: {typeof(T)} Id: {entity.Id}.");
                }

                _logger.LogInformation(JsonConvert.SerializeObject(EventObjectFactory <T> .CreateEventObject(entity, eventType), IgnoreReferenced()));
            }
            catch (DbUpdateException ex)
            {
                LoggerExtensions.LogErrorWithInnerExceptions(_logger, ex);
                throw;
            }
        }
Example #3
0
        /// <summary>
        /// Delete an entity.
        /// </summary>
        protected void Delete <T>(Expression <Func <T, bool> > condition) where T : class, IIdentifier
        {
            try
            {
                var entity = _context.Set <T>().SingleOrDefault(condition);

                if (entity == null)
                {
                    throw new NotFoundException("Object to delete not found.");
                }

                _context.Remove(entity);

                SaveChanges(entity, EventType.Delete);

                _logger.LogInformation(JsonConvert.SerializeObject(EventObjectFactory <T> .CreateEventObject(entity, EventType.Delete), IgnoreReferenced()));
            }
            catch (InvalidOperationException ex)
            {
                LoggerExtensions.LogErrorWithInnerExceptions(_logger, ex);
                throw new TooManyFoundException(ex.Message, ex);
            }
        }