Пример #1
0
        private static async Task <TEntity> GetOrCreateEntityAsync <TEntity>(NesteoDbContext dbContext, Expression <Func <TEntity, bool> > predicate,
                                                                             Func <TEntity> factoryFunc) where TEntity : class
        {
            // Get db set
            DbSet <TEntity> dbSet = dbContext.Set <TEntity>();

            // If the entity exists in the local snapshot, return it directly
            TEntity entity = dbSet.Local.FirstOrDefault(predicate.Compile());

            if (entity != null)
            {
                return(entity);
            }

            // Search the entity in the database
            entity = await dbSet.FirstOrDefaultAsync(predicate).ConfigureAwait(false);

            if (entity != null)
            {
                return(entity);
            }

            // Entity doesn't exist yet. Create a new one
            entity = factoryFunc.Invoke();
            return(dbSet.Add(entity).Entity);
        }
Пример #2
0
 protected CrudServiceBase(NesteoDbContext dbContext, IMapper mapper)
 {
     DbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
     Mapper    = mapper ?? throw new ArgumentNullException(nameof(mapper));
     Entities  = dbContext.Set <TEntity>();
 }