public async Task <string> CreateAsync(Video video) { videoRepository.Add(video); await videoRepository.SaveChangesAsync(); return(video.Id); }
public async Task AddProduct(ProductCreateInputModel model, string imagePath) { Product product = new Product { Name = model.Name, Price = model.Price, CategoryId = model.CategoryId, Description = model.Description, }; Directory.CreateDirectory($"{imagePath}/products/"); var extension = Path.GetExtension(model.Image.FileName).TrimStart('.'); if (!this.allowedExtensions.Any(x => extension.EndsWith(x))) { throw new Exception($"Invalid image extension {extension}"); } var dbImage = new Image { Extension = extension, }; product.Image = dbImage; var physicalPath = $"{imagePath}/products/{dbImage.Id}.{extension}"; using Stream fileStream = new FileStream(physicalPath, FileMode.Create); await model.Image.CopyToAsync(fileStream); await productRepository.AddAsync(product); await productRepository.SaveChangesAsync(); }
public async Task CreateAsync(GradeInputModel inputModel) { var studentSubject = _studentSubjectsRepository.All().FirstOrDefault(s => s.StudentId == inputModel.StudentId && s.SubjectId == inputModel.SubjectId); if (studentSubject != null) { var teacher = _teachersRepository.All().FirstOrDefault(t => t.Id == inputModel.TeacherId); if (teacher != null) { var grade = new Grade { Value = inputModel.Value, Period = inputModel.Period, Type = inputModel.Type, StudentSubject = studentSubject, Teacher = teacher }; await _gradesRepository.AddAsync(grade); await _gradesRepository.SaveChangesAsync(); return; } throw new ArgumentException($"Sorry, we couldn't find teacher with id {inputModel.TeacherId}"); } throw new ArgumentException($"Sorry, we couldn't find pair of student ({inputModel.StudentId}) and subject({inputModel.SubjectId})"); }
public async Task <bool> BanByUsernameAsync(string username) { var user = await userRepository.All() .Include(u => u.Uploads) .Include(u => u.Ratings) .Include(u => u.Comments) .SingleOrDefaultAsync(u => u.UserName == username); if (user == null) { return(false); } foreach (var rate in user.Ratings) { await rateService.DeleteByIdAsync(rate.Id); } foreach (var comment in user.Comments) { await commentSerivce.DeleteByIdAsync(comment.Id); } foreach (var video in user.Uploads) { await videoService.DeleteByIdAsync(video.Id); } userRepository.Delete(user); await userRepository.SaveChangesAsync(); return(true); }
public async Task EditAsync(StudentModifyInputModel modifiedModel) { var student = _studentsRepository.All().FirstOrDefault(s => s.Id == modifiedModel.Id); if (student != null) { var inputModel = modifiedModel.Student; student.FirstName = inputModel.FirstName; student.LastName = inputModel.LastName; student.BirthDate = inputModel.BirthDate; student.PersonalIdentificationNumber = inputModel.PersonalIdentificationNumber; var schoolId = int.Parse(inputModel.SchoolId); var school = _schoolsRepository.All().FirstOrDefault(s => s.Id == schoolId); if (school != null) { student.School = school; var classId = int.Parse(inputModel.ClassId); if (school.Classes.Any(c => c.Id == classId)) { student.Class = school.Classes.FirstOrDefault(c => c.Id == classId); } } _studentsRepository.Update(student); await _studentsRepository.SaveChangesAsync(); } }
public async Task <T> CreateTeacher <T>(TeacherInputModel inputModel) { var schoolId = int.Parse(inputModel.SchoolId); var school = _schoolsRepository.All().FirstOrDefault(s => s.Id == schoolId); if (school != null) { var teacher = new Teacher() { FirstName = inputModel.FirstName, LastName = inputModel.LastName, School = school, UniqueId = _idGeneratorService.GenerateTeacherId() }; await _teachersRepository.AddAsync(teacher); await _teachersRepository.SaveChangesAsync(); BasePersonModel baseModel = _teachersRepository.All().FirstOrDefault(t => t.UniqueId == teacher.UniqueId); return(AutoMapperConfig.MapperInstance.Map <T>(baseModel)); } throw new ArgumentException($"Sorry, we couldn't find school with id {schoolId}"); }
public async Task SetUserEmail(string uniqueId, string email) { if (!string.IsNullOrEmpty(uniqueId)) { var hasDeletedRecord = false; switch (uniqueId[0]) { case GlobalConstants.TeacherIdPrefix: var teacherRecord = _teachersRepository.All().FirstOrDefault(p => p.UniqueId == uniqueId); teacherRecord.Email = email; _teachersRepository.Update(teacherRecord); await _teachersRepository.SaveChangesAsync(); break; case GlobalConstants.StudentIdPrefix: var studentRecord = _studentsRepository.All().FirstOrDefault(p => p.UniqueId == uniqueId); studentRecord.Email = email; studentRecord.Username = email; _studentsRepository.Update(studentRecord); await _studentsRepository.SaveChangesAsync(); break; case GlobalConstants.ParentIdPrefix: var parentRecord = _parentsRepository.All().FirstOrDefault(p => p.UniqueId == uniqueId); parentRecord.Email = email; _parentsRepository.Update(parentRecord); await _parentsRepository.SaveChangesAsync(); break; } } }
public async Task CreateCategory(string name) { var category = new Category { Name = name, }; await categoryRepository.AddAsync(category); await categoryRepository.SaveChangesAsync(); }
public async Task DeleteAsync(int experienceId) { var experience = _experienceRepository.All().FirstOrDefault(e => e.Id == experienceId); if (experience != null) { _experienceRepository.Delete(experience); await _experienceRepository.SaveChangesAsync(); } }
public async Task DeleteAsync(int skillId) { var skill = _skillsRepository.All().FirstOrDefault(e => e.Id == skillId); if (skill != null) { _skillsRepository.Delete(skill); await _skillsRepository.SaveChangesAsync(); } }
public async Task DeleteAsync(int educationId) { var education = _educationEntityRepository.All().FirstOrDefault(e => e.Id == educationId); if (education != null) { _educationEntityRepository.Delete(education); await _educationEntityRepository.SaveChangesAsync(); } }
public async Task <Comment> AddAsync(Comment comment) { repository.Add(comment); await repository.SaveChangesAsync(); var commentFromDb = await repository .All() .Include(c => c.Author) .SingleOrDefaultAsync(c => c.Id == comment.Id); return(commentFromDb); }
public async Task EditAsync(CommentModifyInputModel modifiedModel) { var comment = _commentsRepository.All().FirstOrDefault(c => c.Id == modifiedModel.Id); if (comment != null) { comment.Content = modifiedModel.Content; _commentsRepository.Update(comment); await _commentsRepository.SaveChangesAsync(); } }
public async Task Create(ReviewInputModel input) { var review = AutoMapperConfig.MapperInstance.Map <Review>(input); if (reviewsRepository.AllAsNoTracking().Any(x => x.GameId == input.GameId && x.AuthorId == input.AuthorId)) { await Task.FromException <int>( new InvalidOperationException("A review for this user already exists.")); } await reviewsRepository.AddAsync(review); await reviewsRepository.SaveChangesAsync(); }
public async Task <int> Create(GenreInputModel input) { var genre = new Genre() { Description = input.Description, Name = input.Name, }; await genresRepository.AddAsync(genre); await genresRepository.SaveChangesAsync(); return(genre.Id); }
public async Task <CatalogItem> CreateNew(string name, decimal price, string color) { var catalogItem = new CatalogItem() { Name = name, Price = price, Color = color, }; _catalogItemsRepository.Add(catalogItem); await _catalogItemsRepository.SaveChangesAsync(); return(catalogItem); }
public async Task CreateAsync(ClassInputModel inputModel) { var teacherId = int.Parse(inputModel.TeacherId); var teacher = _teachersRepository.All().FirstOrDefault(t => t.Id == teacherId); if (teacher != null) { if (teacher.Class != null) { throw new ArgumentException($"Sorry, teacher with id {teacherId} is already registered as head of another class"); } var isClassLetterNumberCombinationAlreadyOccupied = _classesRepository.All().Any(c => c.Letter == inputModel.Letter && c.YearCreated == inputModel.YearCreated && c.Year == inputModel.Year && c.Teacher.SchoolId == teacher.SchoolId); if (isClassLetterNumberCombinationAlreadyOccupied) { throw new ArgumentException($"Sorry, there is already existing class for year {inputModel.YearCreated} that's currently in {inputModel.Year} grade and with letter {inputModel.Letter}"); } var schoolClass = new Class { Letter = inputModel.Letter, Year = inputModel.Year, YearCreated = inputModel.YearCreated, Teacher = teacher }; await _classesRepository.AddAsync(schoolClass); await _classesRepository.SaveChangesAsync(); var classEntity = _classesRepository.All().First(c => c.Letter == schoolClass.Letter && c.YearCreated == schoolClass.YearCreated && c.Year == schoolClass.Year); var school = teacher.School; school.Classes.Add(classEntity); _schoolsRepository.Update(school); await _schoolsRepository.SaveChangesAsync(); return; } throw new ArgumentException($"Sorry, we couldn't find teacher with id {teacherId}"); }
public async Task DeleteAsync(int id) { var student = _studentsRepository.All().FirstOrDefault(s => s.Id == id); if (student != null) { var parentIds = student.StudentParents.Select(sp => sp.ParentId).ToList(); foreach (var parentId in parentIds) { var parent = _parentRepository.All().FirstOrDefault(p => p.Id == parentId); var parentStudentsCount = parent?.StudentParents.Count; if (parentStudentsCount == 1) // delete parent if current student is their only child with active account { _parentRepository.Delete(parent); await _parentRepository.SaveChangesAsync(); } var mapping = _studentParentsMappingRepository.All() .FirstOrDefault(sp => sp.StudentId == id && sp.ParentId == parentId); _studentParentsMappingRepository.Delete(mapping); } await _studentParentsMappingRepository.SaveChangesAsync(); // ToDo: Decide if StudentSubject should be handled here as well _studentsRepository.Delete(student); await _studentsRepository.SaveChangesAsync(); } }
public async Task <int> Create(string id, string userId) { var package = _packageRepository.All() .SingleOrDefault(p => p.Id.Equals(id) && p.RecipientId.Equals(userId)); if (package == null) { return(0); } var price = (decimal)package.Weight * 2.67M; var receipt = new Receipt { Fee = price, RecipientId = package.RecipientId, Recipient = package.Recipient, PackageId = package.Id, Package = package, }; var status = _statusRepository.All().SingleOrDefault(s => s.Name.Equals("Acquired")); package.Status = status; _packageRepository.Update(package); await _packageRepository.SaveChangesAsync(); await _receiptRepository.AddAsync(receipt); return(await _receiptRepository.SaveChangesAsync()); }
private async Task <string> CreateUserAsync(string email, string name, string lastName, IDeletableEntityRepository <ApplicationUser> repo) { var user = new ApplicationUser() { FirstName = name, LastName = lastName, Email = email, UserName = email, ProfilePicture = "Test.com", ModelInformation = new ModelInformation { Age = 13, Bust = 14, Waist = 16, Hips = 14, Height = 15, Gender = Gender.Male, Ethnicity = Ethnicity.Chinese, }, UserImages = new List <UserImage> { new UserImage { ImageUrl = "Test" }, }, }; await repo.AddAsync(user); await repo.SaveChangesAsync(); return(user.Id); }
//private async Task<string> CreateUserImages(string userId, IDeletableEntityRepository<UserImage> imageRepo, IDeletableEntityRepository<ApplicationUser> repo) //{ // var userImages = new List<UserImage> // { // new UserImage { UserId = userId, ImageUrl = "testUrl1" }, // new UserImage { UserId = userId, ImageUrl = "testUrl2" }, // new UserImage { UserId = userId, ImageUrl = "testUrl3" }, // }; // foreach (var image in userImages) // { // await imageRepo.AddAsync(image); // await repo.SaveChangesAsync(); // } // return userId; //} private async Task <string> CreateUserWithImage(string email, string name, string lastName, IDeletableEntityRepository <ApplicationUser> repo) { var user = new ApplicationUser() { FirstName = name, LastName = lastName, Email = email, UserName = email, UserImages = new List <UserImage> { new UserImage { ImageUrl = "testUrl1" }, new UserImage { ImageUrl = "testUrl2" }, new UserImage { ImageUrl = "testUrl3" }, }, }; await repo.AddAsync(user); await repo.SaveChangesAsync(); return(user.Id); }
public async Task <IActionResult> Edit(int id, [Bind("Name,UserId,AccountId,IsDeleted,DeletedOn,CreatedOn, Id,ModifiedOn,Stage")] Deal deal) { if (id != deal.Id) { return(NotFound()); } if (ModelState.IsValid) { try { dealRepository.Update(deal);//context.Update(deal); await dealRepository.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DealExists(deal.Id)) { return(NotFound()); } else { throw; } } } ViewData["UserId"] = new SelectList(context.Users, "Id", "FirstName", deal.UserId); ViewData["AccountId"] = new SelectList(context.Accounts, "Id", "Id", deal.AccountId); return(this.RedirectToAction("GetAll")); }
public async Task Add(QuestionTypeInputModel model) { QuestionType questionType = model.To <QuestionType>(); await repository.AddAsync(questionType); await repository.SaveChangesAsync(); }
public async Task AddReservation(ReservationCreateInputModel model) { var reservation = new Reservation { StartTime = model.StartTime, NumberOfSeats = model.NumberOfSeats, Duration = model.Duration, PersonEmail = model.Email, PersonName = model.Name, PersonNumber = model.Number, }; await reservationRepository.AddAsync(reservation); await reservationRepository.SaveChangesAsync(); }
public async Task Add(SubjectInputModel model) { Subject subject = model.To <Subject>(); await repository.AddAsync(subject); await repository.SaveChangesAsync(); }
public async Task <bool> CreateDocument(string name, IFormFile file) { int result = -1; using (var memoryStream = new MemoryStream()) { file.CopyTo(memoryStream); // Upload the file if less than 8 MB if (memoryStream.Length <= 8388608) { var fileforDb = new Document() { Name = name, Bytes = memoryStream.ToArray(), Size = memoryStream.Length, CreatedOn = DateTime.Now, }; repository.Add(fileforDb); result = await repository.SaveChangesAsync(); } return(result > 0 ? true : false); } }
public async Task CreateOrder(Order order) { if (order.Delivery == true) { order.Status = GlobalConstants.Sent; } else { order.Status = GlobalConstants.Open; } orderRepository.AddAsync(order).Wait(); await orderRepository.SaveChangesAsync(); await orderItemService.CreateOrderItem(order); }
public async Task <T> CreatePrincipal <T>(PrincipalInputModel inputModel) { var principal = new Principal { FirstName = inputModel.FirstName, LastName = inputModel.LastName, UniqueId = _idGeneratorService.GeneratePrincipalId() }; await _principalsRepository.AddAsync(principal); await _principalsRepository.SaveChangesAsync(); BasePersonModel baseModel = _principalsRepository.All().FirstOrDefault(p => p.FirstName == inputModel.FirstName && p.LastName == inputModel.LastName); return(AutoMapperConfig.MapperInstance.Map <T>(baseModel)); }
public async Task <int> Create(ContactFormInputModel input) { var contactForm = AutoMapperConfig.MapperInstance.Map <ContactForm>(input); await contactFormsRepository.AddAsync(contactForm); await contactFormsRepository.SaveChangesAsync(); return(contactForm.Id); }
public async Task DeleteOrder(int orderId) { var order = await this.GetOrderByIdAsync(orderId); await orderItemService.DeleteOrderItemsByOrderId(orderId); orderRepository.Delete(order); await orderItemRepository.SaveChangesAsync(); }