Beispiel #1
0
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.CreateAsync(TEntity)"/>
        public override async Task <(bool success, Guid id)> CreateAsync(TrainingSession entity)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            bool saveSuccess;

            try
            {
                EntityValidator.Validate(entity);
                DbContext.Entry(entity.TrainingRoom).State = EntityState.Unchanged;
                DbContext.Set <TrainingSession>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                // Force the DbContext to fetch the species anew on next query.
                foreach (TrainingSession session in entity.TrainingRoom.TrainingSessions)
                {
                    DbContext.Entry(session).State = EntityState.Detached;
                }
                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                CreatingEntityFailedException creatingEntityFailedException = new CreatingEntityFailedException($"The entity of type {typeof(TrainingSession).Name} could not be created.", ex);
                Logger.LogError(creatingEntityFailedException, creatingEntityFailedException.Message);
                throw creatingEntityFailedException;
            }
            return(success : saveSuccess, id : entity.Id);
        }
Beispiel #2
0
        private static bool GetValue(Type entityType, object entity, PropertyInfo property, dynamic dto)
        {
            string propertyTypeName = property.PropertyType.Name.Replace("Proxy", "").Replace("Dto", "");

            // TODO: Verify if the current "Entity" type has a DTO type. if not throw!
            // TODO: also check if the property name is not equal to an Entity by chance... so maybe try to check for standard types?
            if (!typeof(UserDto).Assembly.GetTypes().Any(t => t.Name.Equals(propertyTypeName + "Dto")))
            {
                return(false);
            }
            Type   newEntityType = typeof(User).Assembly.GetTypes().First(t => t.Name.Equals(propertyTypeName));
            object entityObject;

            // NOTE: Because of lazy loading the database will need to be locked to ensure no parallel queries are running (which will throw errors).
            // This will use the shared globally shared LoadLock.
            if (property.PropertyType.Name.Contains("Proxy"))
            {
                using EntityLoadLock.Releaser lazyLoadLock = EntityLoadLock.Shared.Lock();
                entityObject = entityType.GetProperty(property.Name)?.GetValue(entity, null);
            }
            else
            {
                entityObject = entityType.GetProperty(property.Name)?.GetValue(entity, null);
            }

            if (entityObject == null)
            {
                return(false);
            }

            object result = Convert(property.PropertyType, newEntityType, entityObject);

            property.SetValue(dto, result);
            return(true);
        }
Beispiel #3
0
        /// <inheritdoc cref="IRepository{TEntity}.DeleteAsync(TEntity)"/>
        public virtual async Task <bool> DeleteAsync(TEntity entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                if (!await DbContext.Set <TEntity>().ContainsAsync(entity))
                {
                    throw new EntityNotFoundException($"The entity of type {typeof(TEntity).Name} could not be found.");
                }

                DbContext.Set <TEntity>().Remove(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                DeletingEntityFailedException deletingEntityFailedException = new DeletingEntityFailedException($"The entity of type {typeof(TEntity).Name} could not be deleted.", ex);
                Logger.LogError(deletingEntityFailedException, deletingEntityFailedException.Message);
                throw deletingEntityFailedException;
            }
            return(saveSuccess);
        }
Beispiel #4
0
        /// <inheritdoc cref="ITrainingSessionRepository.InsertFirstGenerationAsync(TrainingSession)"/>
        public async Task InsertFirstGenerationAsync(TrainingSession trainingSession)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                foreach (Species species in trainingSession.TrainingRoom.Species.Where(species => DbContext.Entry(species).State != EntityState.Unchanged))
                {
                    MarkSpeciesAsAdded(species);
                }

                foreach (LeasedOrganism leasedOrganism in trainingSession.LeasedOrganisms)
                {
                    DbContext.Entry(leasedOrganism).State = EntityState.Added;
                }

                await DbContext.SaveChangesAsync();

                DbContext.Update(trainingSession.TrainingRoom);

                await DbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Message);
                throw;
            }
        }
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.FindSingleByExpressionAsync"/>
        public override async Task <TrainingSession> FindSingleByExpressionAsync(Expression <Func <TrainingSession, bool> > predicate)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            TrainingSession entity = await TrainingSessionSetWithInclude().Where(predicate).SingleOrDefaultAsync();

            if (entity == default)
            {
                Console.WriteLine(new EntityNotFoundException($"The entity of type {typeof(TrainingSession).Name} could not be found by the predicate."));
            }
            return(entity);
        }
        /// <inheritdoc cref="IRepository{TEntity}.FindSingleByExpressionAsync(Expression{Func{TEntity, bool}})"/>
        public virtual async Task <TEntity> FindSingleByExpressionAsync(Expression <Func <TEntity, bool> > predicate)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            TEntity entity = await DbContext.Set <TEntity>().SingleOrDefaultAsync(predicate);

            if (entity == default)
            {
                Console.WriteLine(new EntityNotFoundException($"The entity of type {typeof(TEntity).Name} could not be found by the predicate."));
            }
            return(entity);
        }
Beispiel #7
0
        /// <inheritdoc cref="ITrainingSessionRepository.UpdateOrganismsAsync(TrainingSession)"/>
        public async Task UpdateOrganismsAsync(TrainingSession trainingSession)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                foreach (Species species in trainingSession.TrainingRoom.Species)
                {
                    Logger.LogInformation($"{species.GetType()} -> {DbContext.Entry(species).State} | Organisms: {species.Organisms.Count}");
                    if (DbContext.Entry(species).State == EntityState.Detached)
                    {
                        MarkSpeciesAsAdded(species);
                        continue;
                    }
                    foreach (Organism organism in species.Organisms)
                    {
                        bool newGenes = false;
                        foreach (ConnectionGene connectionGene in organism.ConnectionGenes)
                        {
                            if (DbContext.Entry(connectionGene).State != EntityState.Added)
                            {
                                continue;
                            }
                            newGenes = true;
                            break;
                        }
                        if (newGenes)
                        {
                            DbContext.Entry(organism).State = EntityState.Added;
                        }
                    }
                }

                foreach (EntityEntry entityEntry in DbContext.ChangeTracker.Entries()
                         .Where(e => e.State == EntityState.Modified && (e.Entity.GetType() == typeof(InputNode) || e.Entity.GetType() == typeof(OutputNode))))
                {
                    DbContext.Entry(entityEntry.Entity).State = EntityState.Added;
                }
                await DbContext.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                Logger.LogError(ex, ex.Message);
                throw;
            }
        }
Beispiel #8
0
        /// <inheritdoc cref="IRepository{TEntity, TId}.ExistsAsync(Expression{Func{TEntity, bool}})"/>
        public async Task <bool> SaveChangesAsync()
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            bool saveSuccess = false;

            try
            {
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                SavingChangesFailedException exception = new SavingChangesFailedException("The changes failed to save.", ex);
                Logger.Log(LogLevel.Error, exception, exception.Message);
            }
            return(saveSuccess);
        }
        /// <inheritdoc cref="IRepository{TEntity}.UpdateAsync(TEntity)"/>
        public virtual async Task <bool> UpdateAsync(TEntity entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            DbContext.Update(entity);
            try
            {
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(new UpdatingEntityFailedException($"The entity of type {typeof(TEntity).Name} failed to update.", ex));
            }
            return(saveSuccess);
        }
        /// <inheritdoc cref="IRepository{TEntity}.CreateAsync(TEntity)"/>
        public virtual async Task <bool> CreateAsync(TEntity entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                EntityValidator.Validate(entity);
                DbContext.Set <TEntity>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(new CreatingEntityFailedException($"The entity of type {typeof(TEntity).Name} could not be created.", ex));
            }
            return(saveSuccess);
        }
Beispiel #11
0
        /// <inheritdoc cref="IRepository{TEntity, TId}.UpdateAsync(TEntity)"/>
        public virtual async Task <(bool success, TId id, bool updated)> UpdateAsync(TEntity entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            EntityEntry <TEntity> entry = DbContext.Update(entity);

            try
            {
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                UpdatingEntityFailedException exception = new UpdatingEntityFailedException($"The entity of type {typeof(TEntity).Name} failed to update.", ex);
                Logger.Log(LogLevel.Error, exception, exception.Message);
            }
            return(success : saveSuccess, id : entity.Id, updated : entry.State == EntityState.Modified);
        }
Beispiel #12
0
        /// <inheritdoc cref="IRepository{TEntity, TId}.CreateAsync(TEntity)"/>
        public virtual async Task <(bool success, TId id)> CreateAsync(TEntity entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                EntityValidator.Validate(entity);
                DbContext.Set <TEntity>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                CreatingEntityFailedException exception = new CreatingEntityFailedException($"The entity of type {typeof(TEntity).Name} could not be created.", ex);
                Logger.Log(LogLevel.Error, exception, exception.Message);
            }
            return(success : saveSuccess, id : entity.Id);
        }
Beispiel #13
0
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.CreateAsync(TEntity)"/>
        public override async Task <(bool success, Guid id)> CreateAsync(TrainingRoom entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                EntityValidator.Validate(entity);
                DbContext.Entry(entity.Owner).State = EntityState.Unchanged;
                DbContext.Set <TrainingRoom>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                CreatingEntityFailedException creatingEntityFailedException = new CreatingEntityFailedException($"The entity of type {typeof(TrainingRoom).Name} could not be created.", ex);
                Logger.LogError(creatingEntityFailedException, creatingEntityFailedException.Message);
            }
            return(saveSuccess, entity.Id);
        }
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.CreateAsync(TEntity)"/>
        public override async Task <bool> CreateAsync(TrainingRoom entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            try
            {
                DbContext.Entry(entity.Owner).State = EntityState.Unchanged;
                EntityValidator.Validate(entity);
                DbContext.Set <TrainingRoom>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(new CreatingEntityFailedException($"The entity of type {typeof(TrainingRoom).Name} could not be created.", ex));
            }

            return(saveSuccess);
        }
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.UpdateAsync(TEntity)"/>
        public override async Task <bool> UpdateAsync(TrainingSession entity)
        {
            bool saveSuccess = false;

            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            DbContext.Update(entity);
            try
            {
                int saveResult = await DbContext.SaveChangesAsync();

                // Force the DbContext to fetch the species anew on next query.
                foreach (Species species in entity.TrainingRoom.Species)
                {
                    DbContext.Entry(species).State = EntityState.Detached;
                }
                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(new UpdatingEntityFailedException($"The entity of type {typeof(TrainingSession).Name} failed to update.", ex));
            }
            return(saveSuccess);
        }
Beispiel #16
0
 /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.FindManyByExpressionAsync"/>
 public override async Task <IEnumerable <TrainingRoom> > FindManyByExpressionAsync(Expression <Func <TrainingRoom, bool> > predicate)
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await TrainingRoomSetWithInclude().Where(predicate).ToListAsync());
 }
Beispiel #17
0
 /// <inheritdoc cref="IRepository{TEntity, TId}.GetPaginationAsync(int, int)"/>
 public virtual async Task <IEnumerable <TEntity> > GetPaginationAsync(int pageNumber, int pageSize)
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await DbContext.Set <TEntity>().Skip(pageNumber * pageSize).Take(pageSize).ToListAsync());
 }
 /// <inheritdoc cref="IRepository{TEntity}.FindManyByExpressionAsync(Expression{Func{TEntity, bool}})"/>
 public virtual async Task <IEnumerable <TEntity> > FindManyByExpressionAsync(Expression <Func <TEntity, bool> > predicate)
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await DbContext.Set <TEntity>().Where(predicate).ToListAsync());
 }
 /// <inheritdoc cref="IRepository{TEntity}.ExistsAsync(Expression{Func{TEntity, bool}})"/>
 public virtual async Task <bool> ExistsAsync(Expression <Func <TEntity, bool> > predicate)
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await DbContext.Set <TEntity>().AnyAsync(predicate));
 }
Beispiel #20
0
 /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.GetAllAsync"/>
 public override async Task <IEnumerable <TrainingRoom> > GetAllAsync()
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await TrainingRoomSetWithInclude().ToListAsync());
 }
 /// <inheritdoc cref="IRepository{TEntity}.GetAllAsync"/>
 public virtual async Task <IEnumerable <TEntity> > GetAllAsync()
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await DbContext.Set <TEntity>().ToListAsync());
 }
 /// <inheritdoc cref="IRepository{TEntity}.FindSingleOrDefaultAsync(Expression{Func{TEntity, bool}})"/>
 public virtual async Task <TEntity> FindSingleOrDefaultAsync(Expression <Func <TEntity, bool> > predicate)
 {
     using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
     return(await DbContext.Set <TEntity>().SingleOrDefaultAsync(predicate));
 }