public void CreateAsync_ReturnsCorrectPhoneId() { var options = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var dbContext = new ApplicationDbContext(options)) { CreatePhoneServiceModel phone = new CreatePhoneServiceModel { PhoneNumber = "0897248721", }; var phonesService = new PhonesService(dbContext); var result = phonesService.CreateAsync(phone); Assert.Equal(1, result.Result); } }
public async Task <IActionResult> CreatePhone(PhoneInputModel model) { this.FillUnifiedModel(); if (!this.ModelState.IsValid) { return(this.View("Create", this.unifiedModel)); } var phone = new CreatePhoneServiceModel { PhoneNumber = model.PhoneNumber, }; await this.phonesService.CreateAsync(phone); return(this.RedirectToAction("Create")); }
//--------------- METHODS ----------------- /// <summary> /// Creates a new <see cref="Phone"/> using the <see cref="CreatePhoneServiceModel"/>. /// If such <see cref="Phone"/> already exists in the database, fetches it's (int)<c>Id</c> and returns it. /// If such <see cref="Phone"/> doesn't exist in the database, adds it and return it's (int)<c>Id</c>. /// </summary> /// <param name="model">Service model with <c>PhoneNumber</c></param> /// <returns>PhoneNumber ID</returns> public async Task <int> CreateAsync(CreatePhoneServiceModel model) { int phoneNumberId = this.dbContext.Phones.Where(x => x.PhoneNumber == model.PhoneNumber) .Select(x => x.Id) .FirstOrDefault(); if (phoneNumberId != 0) // If phoneNumberId is different than 0 (int default value), phone with such phoneNumber already exists, so return it's id. { return(phoneNumberId); } Phone phone = new Phone { PhoneNumber = model.PhoneNumber, }; await this.dbContext.Phones.AddAsync(phone); await this.dbContext.SaveChangesAsync(); return(phone.Id); }