public virtual async Task <TKey> AddAsync(TModelAdd model) { var entity = _dataMapper.Parse <TModelAdd, TEntity>(model); await _repository.AddAsync(entity); return(entity.Id); }
public void T1Add() { //Add Bloco var blocoAdd = new Bloco() { Descricao = "Bloco A" }; var addBloco = _blocoRepository.AddAsync(blocoAdd); Assert.True(addBloco.IsCompletedSuccessfully); //Add Bloco var blocoAdd2 = new Bloco() { Descricao = "Bloco B" }; var addBloco2 = _blocoRepository.AddAsync(blocoAdd2); Assert.True(addBloco2.IsCompletedSuccessfully); //Add Apartamento var apartamentoAdd = new Apartamento() { Bloco = blocoAdd, Numero = 1, Moradores = new List <Morador>() }; var addApartamento = _apartamentoRepository.AddAsync(apartamentoAdd); Assert.True(addApartamento.IsCompletedSuccessfully); //Add Apartamento var apartamentoAdd2 = new Apartamento() { Bloco = blocoAdd2, Numero = 125, Moradores = new List <Morador>() }; var addApartamento2 = _apartamentoRepository.AddAsync(apartamentoAdd); Assert.True(addApartamento2.IsCompletedSuccessfully); //Add Moradores var moradoresAdd = new List <Morador>(); for (int i = 0; i < 10; i++) { var moradorAdd = new Morador() { Cpf = 01988377129, DataNascimento = Convert.ToDateTime("28/06/1985"), Fone = "61993766328", NomeCompleto = "Vitão " + i.ToString(), Apartamento = apartamentoAdd }; moradoresAdd.Add(moradorAdd); } var addMoradores = _moradorRepository.AddAsync(moradoresAdd); Assert.True(addApartamento.IsCompletedSuccessfully); //Save Changes var saveChanges = _mainContext.SaveChangesAsync(); Assert.True(saveChanges.IsCompletedSuccessfully); }
/// <summary> /// Thêm mới bản ghi vào CSDL /// </summary> /// <param name="entity"></param> /// <param name="returnSingleValue">Có trả về dữ liệu tùy chọn từ store hay không</param> /// <returns></returns> public async virtual Task <ActionServiceResult> Insert(T entity, bool returnSingleValue = false) { if (Validate(entity) == true) { var res = await _baseRepository.AddAsync(entity, returnSingleValue); if (res == null) { return new ActionServiceResult { Success = false, Code = Code.ErrorAddEntity, Message = Resources.ErrorAddEntity, } } ; return(new ActionServiceResult { Success = true, Code = Code.Success, Message = Resources.Success, Data = res }); } else { return new ActionServiceResult { Success = false, Code = Code.ValidateBussiness, Message = Resources.ValidateBussiness, Data = null } }; }
/// <summary> /// 添加 /// </summary> /// <param name="input">信息</param> /// <param name="roleIds">角色Id</param> /// <returns>信息</returns> public async Task <UserListDto> AddAsync(UserEditDto input, List <int> roleIds) { #region 用户 if (await CurrentRepository.IsExistsAsync(u => u.UserName == input.UserName)) { throw new UserFriendlyException("用户名已存在"); } User user = Mapper.Map <User>(input); user.CanUse = true; user.Password = _configuration["AppSetting:DefaultPassword"]; user = await CurrentRepository.AddAsync(user); #endregion 用户 #region 角色 if (roleIds != null && roleIds.Any()) { await _userRoleRepository.AddRangeAsync(roleIds .Select(r => new UserRole() { UserID = user.ID, RoleID = r })); } #endregion 角色 await CurrentContext.SaveChangesAsync(); return(_mapper.Map <UserListDto>(user)); }
public override async Task <Result> Handle(EditExpertTypeCommand request, CancellationToken cancellationToken) { var id = string.IsNullOrWhiteSpace(request.Id) ? 0 : Convert.ToInt32(request.Id); var sort = Convert.ToInt32(request.Sort); if (id <= 0) //新增 { var item = new Domain.Expert.ExpertType() { Sort = sort, Name = request.Name }; await _expertTypeRepository.AddAsync(item); } else { //修改 var item = await _expertTypeRepository.Set().FirstOrDefaultAsync(x => x.Id == id); if (item == null) { return(Result.Failure($"id={request.Id}内容不存在")); } item.Sort = sort; item.Name = request.Name; await _expertTypeRepository.UpdateAsync(item); } return(Result.Success()); }
/// <summary> /// 添加 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <ApiResult <string> > Add(SysMenuParam model) { var result = new ApiResult <string>(); try { model.Id = Unique.Id(); var menuModel = model.MapTo <SysMenuParam, SysMenu>(m => m.Id); if (model.Parent.Any()) { menuModel.ParentId = model.Parent[model.Parent.Count - 1]; menuModel.ParentGroupId = string.Join(",", model.Parent.ToArray()) + "," + menuModel.Id; //查询,上级的层级 var paramModel = await _thisRepository.GetModelAsync(m => m.Id == menuModel.ParentId); if (paramModel != null && !string.IsNullOrEmpty(paramModel.Id)) { menuModel.Layer = paramModel.Layer + 1; } } menuModel.CreateUser = "******"; await _thisRepository.AddAsync(menuModel); } catch (Exception ex) { result.StatusCode = (int)HttpStatusCode.InternalServerError; result.Message = ex.Message; } return(result); }
public async Task <User> LogUserAsync(LoginCredentials login) { _uiServices.ShowLoading("Login em andamento, aguarde..."); return(await _policies.GetPolicies().ExecuteAsync(async() => { if (!_connectivityService.IsConnected()) { throw new NoInternetException(); } var user = await _api.LogUserAsync(login); if (user == null) { throw new UserNotFoundException(); } await _userRepository.OpenAsyncConnection(); await _userRepository.AddAsync(user); await _userRepository.CloseAsyncConnection(); _sessionManager.StartSession(user); _uiServices.HideLoading(); return user; })); }
public async Task AddAsync(T model) { model.Active = true; model.ModifiedOn = DateTime.Now; model.CreatedOn = DateTime.Now; await repository.AddAsync(model); }
/// <summary> /// 添加 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <ApiResult <string> > Add(SysOrganizeParam model) { var result = new ApiResult <string>(); try { var organizeModel = model.MapTo <SysOrganizeParam, SysOrganize>(m => m.Id); organizeModel.Id = Unique.Id(); organizeModel.ParentId = model.Parent[model.Parent.Count - 1]; organizeModel.ParentIdList = string.Join(",", model.Parent.ToArray()) + "," + organizeModel.Id; organizeModel.CreateUser = "******"; //根据父级查询等级 var parentModel = await _thisRepository.GetModelAsync(m => m.Id == organizeModel.ParentId); if (parentModel != null) { organizeModel.Layer = parentModel.Layer + 1; } await _thisRepository.AddAsync(organizeModel); } catch (Exception ex) { result.StatusCode = (int)HttpStatusCode.InternalServerError; result.Message = ex.Message; } return(result); }
public async Task <ApiResponse <SessionDto> > CreateSession(AppUser user, int gameId) { // Validate if user has access to the game var access = await _userGameService.UserHasGame(user, gameId); if (!access) { return(new ApiResponse <SessionDto>((int)HttpStatusCode.Unauthorized)); } // Create the session var session = new Session { AppUserId = user.Id, GameId = gameId, StartDate = DateTime.Now }; var result = await _sessionRepository.AddAsync(session, true); // Create session dependencies await _sessionCharacterService.CreateSessionCharacters(session); return(new ApiResponse <SessionDto>((int)HttpStatusCode.OK, _mapper.Map <SessionDto>(result))); }
public async Task GeneratePayrollAsync(PayrollRequestDto payrollRequestDto) { foreach (var employee in payrollRequestDto.Employees) { double afpRetention = this.GetAfpRetention(payrollRequestDto.Afp, employee.Salary); double arsRetention = this.GetArsRetention(payrollRequestDto.ARS, employee.Salary); double taxableSalary = employee.Salary - (afpRetention + arsRetention); double isrRetention = this.GetIsrRetention(taxableSalary); await _payrollRepository.AddAsync( new Payroll() { AfpRetention = afpRetention, ArsRetention = arsRetention, EmployeeId = employee.Id, RawSalary = employee.Salary, IsrRetention = isrRetention, TaxableSalary = taxableSalary, NetSalary = taxableSalary - isrRetention, PayrollDate = payrollRequestDto.Date, CreatedAt = DateTime.Now, Status = true } ); } }
public async Task <IActionResult> Post([FromBody] RegistrationViewModel model) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } AppUser appUser = _mapper.Map <AppUser>(model); // UserViewModel viewModel = _mapper.Map<UserViewModel>(user); var result = await _userManager.CreateAsync(appUser, model.Password); if (!result.Succeeded) { return(new OkObjectResult("Failed")); } await _repository.AddAsync(new Customer { IdentityId = appUser.Id, Location = model.Location }); await _repository.SaveAsync(); } catch (Exception ex) { throw ex; } return(new OkObjectResult("Account created")); }
public async Task Add(NewPurchaseModel model) { var newPurchase = new NewPurchase { Date = model.Date, SetNumber = model.SetNumber, SetName = model.SetName, Theme = model.Theme, Promotions = model.Promotions, Price = model.Price, UnitPrice = model.UnitPrice, Quantity = model.Quantity, Parts = model.Parts, TotalParts = model.TotalParts, PriceToPartOutRatio = model.PriceToPartOutRatio, Source = model.Source, PaymentMethod = model.PaymentMethod, AveragePartOutValue = model.AveragePartOutValue, MyPartOutValue = model.MyPartOutValue, ExpectedGrossProfit = model.ExpectedGrossProfit, ExpectedNetProfit = model.ExpectedNetProfit, Status = model.Status, SellingNotes = model.SellingNotes, Notes = model.Notes, Receipt = model.Receipt }; await _repo.AddAsync(newPurchase); }
/// <summary> /// The student takes the next assignment. /// </summary> /// <param name="Id"></param> /// <param name="newAssignment"></param> /// <returns></returns> public async Task TakeAssignmentAsync(Guid Id, AddStudentAssignmentDTO newAssignment) { Func <IIncludable <Student>, IIncludable> include = i => i.Include(p => p.OldAssignments); var currentUser = await _studentRepository.GetAllAsync(include, i => i.AppUser.UserName == _loggedUser).ConfigureAwait(false); var currentStudent = currentUser.First(); currentStudent.ThrowIfNullForGuidObject(); var lastAssignment = currentStudent.OldAssignments.Where(i => i.FinishedDate >= DateTime.UtcNow); if (lastAssignment.Count() > 0) { throw new MilvaUserFriendlyException("UndeliveredHomework"); } var toBeTakeAssignment = await _assignmentRepository.GetByIdAsync(Id, i => i.Level == currentStudent.Level).ConfigureAwait(false); toBeTakeAssignment.ThrowIfNullForGuidObject(); var studentAssignment = new StudentAssigment { IsApproved = false, AssigmentId = toBeTakeAssignment.Id, StudentId = currentStudent.Id, AdditionalTime = newAssignment.AdditionalTime, AdditionalTimeDescription = newAssignment.AdditionalTimeDescription, Status = Entity.Enum.EducationStatus.InProgress }; await _studentAssignmentRepository.AddAsync(studentAssignment).ConfigureAwait(false); await _milvaMailSender.MilvaSendMailAsync(currentStudent.Mentor.AppUser.Email, Helpers.Enums.MailSubject.Information, currentStudent.Name + currentStudent.Surname + " isimli öğrencinin yeni bir ödev isteği var."); }
public async Task <Result> Handle(EditPartyBuildingArticleCommand request, CancellationToken cancellationToken) { var id = string.IsNullOrWhiteSpace(request.Id) ? 0 : Convert.ToInt32(request.Id); var show = request.Show == "1"; var sort = Convert.ToInt32(request.Sort); if (id <= 0) //新增 { var article = new PartyBuildingArticle() { Content = request.Content, Pic = request.Pic, Show = show, Sort = sort, Source = request.Source, Subtitle = request.Subtitle, ThemeTitle = request.ThemeTitle, Status = 0, UserId = request.LoginUser.Id }; if (request.LoginUser.Type == 1) { article.Status = 1; } await _partyBuildingArticleRepository.AddAsync(article); } else { //修改 var article = await _partyBuildingArticleRepository.Set().FirstOrDefaultAsync(x => x.Id == id); if (article == null) { return(Result.Failure($"id={request.Id}错误文章不存在")); } article.Content = request.Content; article.Pic = request.Pic; article.Show = show; article.Sort = sort; article.Source = request.Source; article.Subtitle = request.Subtitle; article.ThemeTitle = request.ThemeTitle; if (request.LoginUser.Type == 1) { article.Status = Convert.ToInt32(request.Status); } else { article.Status = 0; } await _partyBuildingArticleRepository.UpdateAsync(article); } return(Result.Success()); }
public async Task <Result> Handle(UserAddCommand request, CancellationToken cancellationToken) { var type = Convert.ToInt32(request.Type); if (type == 0 && ( string.IsNullOrWhiteSpace(request.RealName) || string.IsNullOrWhiteSpace(request.IDCard) || string.IsNullOrWhiteSpace(request.Mobile))) { return(Result.Failure("姓名、身份证号码、手机号码不能为空!")); } if (await _userRepository.AnyAsync(x => x.UserName == request.UserName)) { return(Result.Failure("用户名已存在")); } var pwd = _md5.Md5(request.Password); var user = new User() { Password = pwd, UserName = request.UserName, Type = type }; if (type == 0 || type == 2) { user.RealName = request.RealName; user.IDCard = request.IDCard; user.Mobile = request.Mobile; } await _userRepository.AddAsync(user, cancellationToken); return(Result.Success()); }
public async Task <TEntity> AddAsync(TEntity entity) { await _repository.AddAsync(entity); await _unitOfWork.CommitAsync(); return(entity); }
public virtual async Task <T> AddAsync(U viewModel, CancellationToken ct = default(CancellationToken)) { var entity = this.PrepareAddData(viewModel); entity = await _repository.AddAsync(entity, ct); return(entity); }
public override async Task <Contact> AddAsync(Contact entity) { var result = await tReposiory.AddAsync(entity); EmailManage.AddEmailQueue(configuration, "Yeni İletişim Formu " + entity.Name + " " + entity.Email, entity.Description, isHtml: false); return(result); }
public async Task <T> AddAsync(T entity) { var e = await _repository.AddAsync(entity); await _repository.CommitAsync(); return(e); }
public async Task StartSessionAsync(User user) { this._loggedUser = user; await _userRepository.RemoveAllAsync(); await _userRepository.AddAsync(user); }
public async Task <TModel> AddAsync(TModel modelToAdd) { if (modelToAdd == null) { throw new ArgumentNullException(nameof(modelToAdd)); } return(await _iBaseRepository.AddAsync(modelToAdd)); }
/// <summary> /// Maps <paramref name="addProfessionDTO"/> to <c><b>Profession</b></c> object and adds that product to repository. /// </summary> /// <param name="addProfessionDTO">Profession to be added.</param> public async Task AddProfessionAsync(AddProfessionDTO addProfessionDTO) { var profession = new Profession { Name = addProfessionDTO.Name, }; await _professionRepository.AddAsync(profession).ConfigureAwait(false); }
public async Task <ModelStateDictionary> CreateAsync(DiaryModel model) { ModelStateDictionary keyValuePairs = new ModelStateDictionary(); var diary = mapper.Map <Diary>(model); //todo valid await diaryRepository.AddAsync(diary); return(keyValuePairs); }
/// <summary> /// Maps <paramref name="addQuestionDTO"/> to <c><b>Question</b></c> object and adds that product to repository. /// </summary> /// <param name="addQuestionDTO">Question to be added.</param> /// <returns></returns> public async Task AddQuestionAsync(AddQuestionDTO addQuestionDTO) { var question = new Question { Title = addQuestionDTO.Title, QuestionContent = addQuestionDTO.QuestionContent, }; await _questionRepository.AddAsync(question).ConfigureAwait(false); }
public async virtual Task <TDTO> CreateAsync(TDTO dto) { TEntity entity = _mapper.Map <TDTO, TEntity>(dto); await _repository.AddAsync(entity); await _unitOfWork.CompleteAsync(); return(_mapper.Map <TEntity, TDTO>(entity)); }
public async Task <bool> RequestNewBankAccount(NewBankAccountRequestViewModel newAccount) { var account = _mapper.Map <BankAccount>(newAccount); account.AccountNumber = Guid.NewGuid().ToString(); account.Approved = null; await _bankAccountRepository.AddAsync(account); return(true); }
public async Task <IActionResult> Create([Bind("Id,Name,LastName,Gender,Salary,Status")] Employee employee) { if (ModelState.IsValid) { await _employeeRepository.AddAsync(employee); return(RedirectToAction(nameof(Index))); } return(View(employee)); }
public async Task <ProductDto> Create(ProductDataDto dto) { validator.Validate(dto); var product = productFactory.Create(dto); var addedProduct = await repository.AddAsync(product); await unitOfWork.SaveAsync(); return(mapper.Map <ProductDto>(addedProduct)); }
public async virtual Task <IActionResult> Add([FromBody] T entity) { if (ModelState.IsValid) { await _repository.AddAsync(entity); return(Ok(entity)); } return(BadRequest(ModelState)); }