public async Task <OrderModel> CreateOrderAsync(OrderModel model)
        {
            var customer = await _context.Set <Customer>().Where(c => c.UserID == model.UserId).SingleOrDefaultAsync();

            var newOrder = new Order
            {
                OrderDate            = DateTime.Now,
                IsCanceled           = true,
                TotalPrice           = model.TotalPrice,
                StartPreparationTime = model.PickupTime,
                Customer             = customer,
            };

            var orderDetail = new OrderDetail();

            orderDetail.CoffeeId = model.CoffeeId;
            orderDetail.Order    = newOrder;
            orderDetail.Quantity = model.Quantity;

            await _context.AddAsync(newOrder);

            await _context.AddAsync(orderDetail);

            await _context.SaveChangesAsync();

            return(new OrderModel().Assign(newOrder));
        }
예제 #2
0
        public async Task <List <T> > InserirAsync(List <T> entidades)
        {
            ValidarInserirEntidades(entidades);

            foreach (T entidade in entidades)
            {
                try
                {
                    bool exists = dbService.Set <T>().Any(ent => ent.Id == entidade.Id);

                    if (!exists)
                    {
                        await dbService.AddAsync(entidade);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine(entidade.GetType() + "de Id:" + entidade.Id + "já foi cadastrada");
                        throw new EntityAlreadyExistsException("Entidade já foi cadastrada");
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    throw new EntityAlreadyExistsException("Não é possível criar uma entidade já existente");
                }
            }
            await dbService.SaveChangesAsync();

            return(entidades);
        }
        /// <exception cref="ServiceException"/>
        /// <exception cref="NotFoundException"/>
        public async Task <Guid> AddAsync(Dtos.Teacher dto)
        {
            var validator           = new Dtos.TeacherValidator();
            ValidationResult result = validator.Validate(dto);

            if (!result.IsValid)
            {
                string errMess = string.Empty;

                foreach (var failure in result.Errors)
                {
                    errMess += $"Property { failure.PropertyName } failed validation. Error was: { failure.ErrorMessage }\n";
                }

                throw new ServiceException(errMess);
            }

            if (!await _context.Set <Entities.Department>().AnyAsync(d => d.Id == dto.DepartmentId))
            {
                throw new InvalidModelException($"Department with id: {dto.DepartmentId} not found");
            }

            var id   = Guid.NewGuid();
            var uiId = Guid.NewGuid();
            var now  = DateTime.UtcNow;

            var userInfo = new Entities.UserInfo
            {
                DateOfBirth  = dto.DateOfBirth,
                PhoneNumber  = dto.PhoneNumber,
                Email        = dto.Email,
                FirstName    = dto.FirstName,
                FirstNameEng = dto.FirstNameEng,
                LastName     = dto.LastName,
                LastNameEng  = dto.LastNameEng,
                Patronymic   = dto.Patronymic,
                Id           = uiId
            };

            await _context.AddAsync(userInfo);

            var teacher = new Entities.Teacher
            {
                Id               = id,
                CreatedAt        = now,
                UpdatedAt        = now,
                AcademicRank     = dto.AcademicRank,
                DepartmentId     = dto.DepartmentId,
                Position         = dto.Position,
                ScientificDegree = dto.ScientificDegree,
                TypeOfEmployment = dto.TypeOfEmployment,
                UserInfoId       = uiId
            };

            await _context.AddAsync(teacher);

            await _context.SaveChangesAsync();

            return(id);
        }
예제 #4
0
        public async Task <Guid> AddAsync(Order order)
        {
            var id     = Guid.NewGuid();
            var entity = new DAL.Entities.Order
            {
                CustomerName         = order.CustomerName,
                DateOrderedUtc       = order.DateOrderedUtc,
                ExpectedDeliveryDate = order.ExpectedDeliveryDate,
                Id = id
            };

            await context.AddAsync(entity);

            foreach (var lineItem in order.LineItems)
            {
                var lineItemEntity = new DAL.Entities.LineItem
                {
                    BookId    = lineItem.BookId,
                    Id        = Guid.NewGuid(),
                    BookPrice = lineItem.BookPrice,
                    NumBooks  = lineItem.NumBooks,
                    OrderId   = id
                };

                await context.AddAsync(lineItemEntity);
            }

            return(id);
        }
        /// <summary>
        /// Allows store the new entities
        /// </summary>
        /// <param name="entitySettings">The settings of the desired CRUD</param>
        /// <param name="entityModel">The entity to save</param>
        /// <returns>True if the store process is successful; else, false</returns>
        private async Task <bool> SaveNewEntity(
            ICrudType entitySettings,
            object entityModel
            )
        {
            ModelState.Remove(entitySettings.Key.Name);
            if (!ModelState.IsValid)
            {
                return(false);
            }
            await DbContext.AddAsync(entityModel);

            try
            {
                await DbContext.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                _logger.LogWarning(ex, "Failure saving changes.");
                AddSaveChangesErrorMessage();
                return(false);
            }

            return(true);
        }
예제 #6
0
        public async Task <DirectoryDTO> CreateRepositoryAsync(int userId, string name)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();

            var root = await _context.AddAsync(new Directory()
            {
                Name = "Root"
            });

            await _context.SaveChangesAsync();

            var repo = await _context.AddAsync(new Repository()
            {
                UserId         = userId,
                Name           = name,
                RootId         = root.Entity.Id,
                LastActivityOn = DateTime.UtcNow
            });

            await _context.SaveChangesAsync();

            await transaction.CommitAsync();

            return(_mapper.Map <DirectoryDTO>(root.Entity));
        }
예제 #7
0
        public virtual Task <int> AddAsync(T entidade)
        {
            _context.AddAsync <T>(entidade);
            _context.Entry <T>(entidade).State = EntityState.Added;

            return(_context.SaveChangesAsync());
        }
예제 #8
0
        public async static Task AddOrUpdateAsync(this DbContext ctx, object entity)
        {
            var entry = ctx.Entry(entity);

            switch (entry.State)
            {
            case EntityState.Detached:
                await ctx.AddAsync(entity);

                break;

            case EntityState.Modified:
                ctx.Update(entity);
                break;

            case EntityState.Added:
                await ctx.AddAsync(entity);

                break;

            case EntityState.Unchanged:
                //item already in db no need to do anything
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #9
0
        public virtual async Task <TEntity> CreateRecordAsync(TEntity record, CancellationToken cancellationToken = default)
        {
            var result = await Context.AddAsync(record, cancellationToken);

            await Context.SaveChangesAsync(cancellationToken);

            return(result.Entity);
        }
예제 #10
0
        public async Task <TEntity> Add(TEntity entity)
        {
            var addedEntity = await DbContext.AddAsync(entity);

            await DbContext.SaveChangesAsync();

            return(addedEntity.Entity);
        }
예제 #11
0
        public virtual async Task <T> AddAsync(T entidade)
        {
            await _context.AddAsync <T>(entidade);

            //_context.Entry<T>(entidade).State = EntityState.Added;

            await _context.SaveChangesAsync();

            return(entidade);
        }
예제 #12
0
        public async Task <FileDTO> UploadFileAsync(int directoryId, string name, string content)
        {
            var path = await _fileStorage.UploadAsync(content);

            var newFile = await _context.AddAsync(new File()
            {
                Name        = name,
                Path        = path,
                DirectoryId = directoryId
            });

            await _context.SaveChangesAsync();

            return(_mapper.Map <FileDTO>(newFile.Entity));
        }
예제 #13
0
        public async Task <UserDTO> GetCurrentUserAsync()
        {
            UserDTO user   = null;
            var     userId = _resolver.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
                var userEntity = await _context.Set <User>().SingleOrDefaultAsync(x => x.Email == userId);

                if (userEntity != null)
                {
                    user = _mapper.Map <UserDTO>(userEntity);
                    return(user);
                }
            }
            var resolvedUser = await _resolver.GetUserAsync();

            if (resolvedUser != null)
            {
                var userEntity = await _context.Set <User>().SingleOrDefaultAsync(x => x.Email == resolvedUser.Email);

                if (userEntity == null)
                {
                    userEntity = (await _context.AddAsync(_mapper.Map <User>(resolvedUser))).Entity;
                    await _context.SaveChangesAsync();
                }
                return(_mapper.Map <UserDTO>(userEntity));
            }

            return(null);
        }
        public async Task SendAsync(LogModel[] logs, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (cancellationToken.IsCancellationRequested)
            {
                await Task.FromCanceled(cancellationToken);
            }

            if (logs.Length == 1)
            {
                // Get DbContext that will be used as a UoW.
                DbContext dbContext = _dbContextProvider.GetDbContext(logs[0]) ?? throw new Exception("Context provider returned null DbContext");
                // Get entity that will persisted.
                Object entity = _dbEntityBuilder.BuildDbEntity(logs[0]) ?? throw new Exception("Entity builder returned null entity");
                // Persist the entity.
                await dbContext.AddAsync(entity);

                await dbContext.SaveChangesAsync(cancellationToken);
            }
            else
            {
                var contexts = new DbContext[logs.Length];
                for (int i = 0; i < logs.Length; i++)
                {
                    DbContext dbContext = _dbContextProvider.GetDbContext(logs[i]) ?? throw new Exception("Context provider returned null DbContext");
                    await dbContext.AddAsync(_dbEntityBuilder.BuildDbEntity(logs[i]) ?? throw new Exception("Entity builder returned null entity"), cancellationToken);

                    contexts[i] = dbContext;
                }
                for (int i = 0; i < contexts.Length; i++)
                {
                    await contexts[i].SaveChangesAsync(cancellationToken);
                }
            }
        }
예제 #15
0
        private async Task _ProcessAddAsync(DbContext context, NubeServerOperation[] operations, Type type)
        {
            var addOperation = operations.Where(o => o.Type == OperationType.Added).First();

            var newItem = _nubeTableTypes[type.Name].Item2();

            if (newItem == null)
            {
                throw new NullReferenceException($"Item of type {type} cannot be created");
            }

            if (newItem is NubeServerTable entity)
            {
                entity.Id              = addOperation.ItemId;
                entity.UserId          = addOperation.UserId;
                entity.ServerUpdatedAt = DateTimeOffset.Now;
            }

            foreach (var operation in operations.Where(o => o.Type == OperationType.Modified))
            {
                _UpdatePropertyFromOperation(newItem, operation, type);
            }

            try
            {
                await context.AddAsync(newItem).ConfigureAwait(false);
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("Operations cannot be added to the store, were these operations already processed?");
            }
        }
예제 #16
0
        public TEntity Insert <TEntity>(TEntity entity) where TEntity : BaseEntity, new()
        {
            context.AddAsync(entity);
            context.SaveChangesAsync();

            return(entity);
        }
        public IActionResult NewUser(NewUserIndexViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            if (DbContext.Users.Any(dbUser => dbUser.Email == viewModel.Email))
            {
                ModelState.AddModelError("Email", "User already exist");
                return(View(viewModel));
            }

            var dbUser = new IdentityUser();

            DbContext.AddAsync(dbUser);

            dbUser.UserName        = viewModel.UserName;
            dbUser.Email           = viewModel.Email;
            dbUser.EmailConfirmed  = true;
            dbUser.NormalizedEmail = viewModel.Email.ToUpper();

            var hasher = new PasswordHasher <IdentityUser>();

            dbUser.PasswordHash = hasher.HashPassword(dbUser, viewModel.Password);

            DbContext.SaveChanges();

            return(RedirectToAction("ListRoles"));
        }
예제 #18
0
        public async Task <JoinChannelResultModel> JoinToGroupChannel(JoinChannelRequestModel model)
        {
            var user = await _authService.GetAuthorizedUser();

            var channel = await DbContext.ChatChannels.FindAsync(model.ChannelId);

            if (channel == null)
            {
                channel = new ChatChannel();

                await DbContext.AddAsync(channel);

                await DbContext.SaveChangesAsync();
            }

            var channelUser = new ChatChannelUser
            {
                UserId    = user.Id,
                ChannelId = channel.Id
            };

            await DbContext.AddAsync(channelUser);

            await DbContext.SaveChangesAsync();

            await _chatProvider.UserJoinedToChannel(user, channel.Id);

            return(new JoinChannelResultModel {
                ChannelId = channel.Id
            });
        }
예제 #19
0
        /// <exception cref="InvalidModelException"/>
        /// <exception cref="NotFoundException"/>
        public async Task <Guid> AddAsync(Dtos.Privilege dto)
        {
            var validator           = new Dtos.PrivilegeValidator();
            ValidationResult result = validator.Validate(dto);

            if (!result.IsValid)
            {
                string errMess = string.Empty;

                foreach (var failure in result.Errors)
                {
                    errMess += $"Property { failure.PropertyName } failed validation. Error was: { failure.ErrorMessage }\n";
                }

                throw new InvalidModelException(errMess);
            }

            var id  = Guid.NewGuid();
            var now = DateTime.UtcNow;

            var privilege = new Entities.Privilege
            {
                Id        = id,
                CreatedAt = now,
                UpdatedAt = now,
                Name      = dto.Name,
            };

            await _context.AddAsync(privilege);

            await _context.SaveChangesAsync();

            return(id);
        }
        /// <summary>
        /// Insert records from url into provided DbSet
        /// </summary>
        /// <typeparam name="T">Type of the desired DbSet entity</typeparam>
        /// <param name="context">Context instance</param>
        /// <param name="url">url which returns mock values</param>
        public static async Task PopulateDbAsync <T>(DbContext context, string url)
            where T : class
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var removeItems = await context.Set <T>().ToArrayAsync();

            context.RemoveRange(removeItems);

            using (HttpClient client = new HttpClient())
                using (Stream stream = await client.GetStreamAsync(url))
                    using (StreamReader sr = new StreamReader(stream))
                        using (JsonReader reader = new JsonTextReader(sr))
                        {
                            JsonSerializer serializer = new JsonSerializer();

                            var items = serializer.Deserialize <T[]>(reader);

                            foreach (var item in items)
                            {
                                await context.AddAsync(item);
                            }
                        }

            await context.SaveChangesAsync();
        }
예제 #21
0
        private void SetUpModelEntity <TEntity>(TDbContext mockedDbContext) where TEntity : class
        {
            var mockedDbSet = DbContext.Set <TEntity>().CreateMockedDbSet();

            var property = typeof(TDbContext).GetProperties().SingleOrDefault(p => p.PropertyType == typeof(DbSet <TEntity>));

            if (property != null)
            {
                property.GetValue(mockedDbContext.Configure()).Returns(callInfo => mockedDbSet);
            }
            else
            {
                Logger.LogDebug("Could not find a DbContext property for type '{type}'", typeof(TEntity));
            }

            mockedDbContext.Configure().Set <TEntity>().Returns(callInfo => mockedDbSet);

            mockedDbContext.Add(Arg.Any <TEntity>()).Returns(callInfo => DbContext.Add(callInfo.Arg <TEntity>()));
            mockedDbContext.AddAsync(Arg.Any <TEntity>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.AddAsync(callInfo.Arg <TEntity>(), callInfo.Arg <CancellationToken>()));

            mockedDbContext.Attach(Arg.Any <TEntity>()).Returns(callInfo => DbContext.Attach(callInfo.Arg <TEntity>()));

            mockedDbContext.Entry(Arg.Any <TEntity>()).Returns(callInfo => DbContext.Entry(callInfo.Arg <TEntity>()));

            mockedDbContext.Find <TEntity>(Arg.Any <object[]>()).Returns(callInfo => DbContext.Find <TEntity>(callInfo.Arg <object[]>()));

            mockedDbContext.FindAsync <TEntity>(Arg.Any <object[]>()).Returns(callInfo => DbContext.FindAsync <TEntity>(callInfo.Arg <object[]>()));
            mockedDbContext.FindAsync <TEntity>(Arg.Any <object[]>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.FindAsync <TEntity>(callInfo.Arg <object[]>(), callInfo.Arg <CancellationToken>()));

            mockedDbContext.Remove(Arg.Any <TEntity>()).Returns(callInfo => DbContext.Remove(callInfo.Arg <TEntity>()));

            mockedDbContext.Update(Arg.Any <TEntity>()).Returns(callInfo => DbContext.Update(callInfo.Arg <TEntity>()));
        }
예제 #22
0
        private async Task <(NubeServerTable, OperationType)> _ProcessAddAsync(
            DbContext context,
            NubeServerOperation[] operations,
            Type type)
        {
            var addOperation = operations.Where(o => o.Type == OperationType.Added).First();

            var newItem = _nubeTableTypes[type.Name].Item2();

            if (newItem == null)
            {
                throw new NullReferenceException($"Item of type {type} cannot be created");
            }

            if (newItem is NubeServerTable entity)
            {
                entity.Id              = addOperation.ItemId;
                entity.UserId          = addOperation.UserId;
                entity.ServerUpdatedAt = DateTimeOffset.Now;

                foreach (var operation in operations.Where(o => o.Type == OperationType.Modified))
                {
                    _UpdatePropertyFromOperation(newItem, operation, type);
                }

                await context.AddAsync(newItem).ConfigureAwait(false);

                return(entity, OperationType.Added);
            }
            else
            {
                throw new InvalidOperationException("Created item is not of type NubeServerTable");
            }
        }
예제 #23
0
        async Task IApplicationStore.CreateAsync(Application application)
        {
            var entity = ApplicationEntity.Create(Guard.ArgumentNotNull(application, nameof(application)), Normalizer);
            await DbContext.AddAsync(entity);

            await DbContext.SaveChangesAsync();
        }
예제 #24
0
        async Task IDelegateConsentStore.AddAsync(string clientId, string userName, IEnumerable <string> scopes)
        {
            clientId = Normalizer.Normalize(Guard.ArgumentNotNullOrWhiteSpace(clientId, nameof(clientId)));
            userName = Normalizer.Normalize(Guard.ArgumentNotNullOrWhiteSpace(userName, nameof(userName)));
            Guard.ElementNotNullOrWhiteSpace(scopes, nameof(scopes), false);
            scopes = scopes.Select(it => Normalizer.Normalize(it)).ToArray();

            var entity = await DbContext.FindAsync <DelegateConsentEntity>(clientId, userName);

            if (null == entity)
            {
                entity = new DelegateConsentEntity
                {
                    ClientId = clientId,
                    UserName = userName,
                    Scopes   = string.Join(Constants.SeperatorString, scopes)
                };
                await DbContext.AddAsync(entity);

                await DbContext.SaveChangesAsync();
            }
            else
            {
                var existingScopes = entity.Scopes.Split(Constants.SeperatorCharacter);
                entity.Scopes = string.Join(Constants.SeperatorString.ToString(), existingScopes.Union(scopes));
                DbContext.Attach(entity);
                DbContext.Update(entity);
            }

            await DbContext.SaveChangesAsync();
        }
예제 #25
0
        protected virtual async Task DefaultInsert(TDomain domain_object)
        {
            var entity = Mapper.Map(domain_object, domain_object.GetType(), typeof(TEntity));
            await context.AddAsync(entity);

            Mapper.Map(entity, domain_object, entity.GetType(), typeof(TDomain));
        }
예제 #26
0
        public async Task <Guid> CreateChat(CreateChatDto payload)
        {
            var chat = new Chat
            {
                Name = payload.Name
            };

            var cm = new List <ChatMember>();

            foreach (var userId in payload.UserIds)
            {
                cm.Add(new ChatMember
                {
                    UserId = userId,
                    Chat   = chat
                });
            }

            await _context.AddAsync(chat);

            await _context.AddRangeAsync(cm);

            await _context.SaveChangesAsync();

            return(chat.Id);
        }
예제 #27
0
        /// <summary>
        /// 插入或更新实体
        /// </summary>
        /// <param name="entity">插入或更新的实体</param>
        /// <param name="autoSave">是否自动保存</param>
        /// <param name="cancellationToken">取消线程标识</param>
        /// <returns></returns>
        public virtual async Task InsertOrUpdateAsync([NotNull] TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            Check.NotNull(entity, nameof(entity));
            var model = await DbContext.FindAsync <TEntity>(entity.GetKeys(), GetCancellationToken(cancellationToken));

            if (model != null)
            {
                //Find实体时已经获得了跟踪对象,先去除跟踪状态
                var entry = DbContext.ChangeTracker.Entries().First(p => p.Entity == model);
                entry.State = EntityState.Detached;

                //再提交更新
                model = entity;
                DbContext.Update(model);
            }
            else
            {
                await DbContext.AddAsync(entity, GetCancellationToken(cancellationToken));
            }

            if (autoSave)
            {
                await DbContext.SaveChangesAsync(GetCancellationToken(cancellationToken));
            }
        }
예제 #28
0
        public virtual async Task <int> AddAsync(TEntity entity)
        {
            int result = 0;

            try
            {
                await _dbContext.AddAsync(entity);

                result = await _dbContext.SaveChangesAsync();
            }
            catch (Exception e)
            {
                throw new OneZeroException("新增失败", e, ResponseCode.UnExpectedException);
            }
            return(result);
        }
예제 #29
0
        public async Task <ServerResponse <AuthorizationTokenResponse> > RegisterAsync(RegistrationRequest request)
        {
            return(await BaseInvokeAsync(async() =>
            {
                if (DbContext.AppUsers.Any(x => x.Email == request.Email || x.Username == request.UserName))
                {
                    throw new UnauthorizedException(Constants.Errors.UserAlreadyRegistered);
                }

                var appUser = new AppUser
                {
                    Username = request.UserName,
                    Email = request.Email,
                    Password = HashPasswordHelper.Hash(request.Password),
                    UserRole = EUserRole.User,
                    CreatedDate = DateTime.Now
                };

                await DbContext.AddAsync(appUser);
                await DbContext.SaveChangesAsync();

                var tokenInfo = _tokenService.CreateToken(GetClaimsFromAppUser(appUser));

                var authorizationTokenResponse = new AuthorizationTokenResponse()
                {
                    Token = tokenInfo.Token,
                    ExpirationDate = tokenInfo.ExpiredDate,
                    AppUserViewModel = Mapper.Map <AppUser, AppUserViewModel>(appUser)
                };

                return ServerResponseBuilder.Build(authorizationTokenResponse);
            }, request));
        }
예제 #30
0
        /// <summary>
        ///     This method is used to generate a URL to verify the user's request such as
        ///     password reset and user's email validation.
        /// </summary>
        /// <param name="user">Register the token with a specific user</param>
        /// <param name="requestType">The type of the request </param>
        /// <param name="ExpiaryDate">The expiry of the token</param>
        /// <returns>The Generate URL</returns>
        private async Task <string> GetUrlWithToken(oUser user, TokenType requestType, DateTime ExpiaryDate)
        {
            /// First check if the user has a token for the requested token type
            IEnumerable <oToken> tokenValues = DbContext.Tokens
                                               .Where(vs => vs.User.Id == user.Id && vs.ValueType == requestType)
                                               .AsNoTracking()
                                               .AsEnumerable();

            /// If the user already has a token for the requested type
            /// then remove all of them
            if (tokenValues != null)
            {
                DbContext.Tokens.RemoveRange(tokenValues);
            }

            /// Create a new token
            var token = new oToken
            {
                User            = user,
                ValueType       = requestType,
                ExpiaryDateTime = ExpiaryDate,
            };

            token.Value = token.GetToken();

            /// Add the new token the context
            await DbContext.AddAsync(token);

            /// Save the changes to the database
            await DbContext.SaveChangesAsync();

            /// return the requested URL
            return(string.Format(@"{0}/{1}/{2}", DomainUrl, requestType, token.Value));
        }