public void Test0070() { #region テストデータ準備 var testEntity = TestUtilLib.GenarateRandomTodoTask(); var testEntity1 = new TodoTask().CopyValuesFrom(testEntity); testEntity1.TodoTaskId = "a"; testEntity1.DueDate = testEntity1.DueDate.Value.AddSeconds(1); var testEntity2 = new TodoTask().CopyValuesFrom(testEntity); testEntity2.TodoTaskId = "c"; var testEntity3 = new TodoTask().CopyValuesFrom(testEntity); testEntity3.TodoTaskId = "b"; using (var context = new EfDbContext()) { context.Add(testEntity1); context.Add(testEntity2); context.Add(testEntity3); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(3, context.TodoTasks.Count()); #endregion List <TodoTask> dbEntities; dbEntities = DalTodoTask.SelectAll(); Assert.AreEqual(3, dbEntities.Count); int i = 0; Assert.AreEqual(testEntity3.TodoTaskId, dbEntities[i++].TodoTaskId); Assert.AreEqual(testEntity2.TodoTaskId, dbEntities[i++].TodoTaskId); Assert.AreEqual(testEntity1.TodoTaskId, dbEntities[i++].TodoTaskId); }
public static async Task Initialize(EfDbContext context) { context.Database.EnsureCreated(); if (context.Products.Count() == 0) { //First product Product product = new Product(); List <Size> size = new List <Size>(); size.Add(new Size(SizeOfPruduct.M, 1)); size.Add(new Size(SizeOfPruduct.L, 1)); size.Add(new Size(SizeOfPruduct.XL, 1)); size.Add(new Size(SizeOfPruduct.XXL, 1)); List <Photos> photosList = new List <Photos>(); photosList.Add(new Photos(@"\Upload\Photos\2d79fb18-0341-4a14-8da1-f7f3edb90a49.jpg")); photosList.Add(new Photos(@"\Upload\Photos\5fb493c8-04b7-4e3d-97d7-bc1cb69dc10a.jpg")); product.Photos = photosList; product.Name = "Jeansy damskie Rocks"; product.Price = 299; product.Description = "Spodnie damskie Rocks<br />Skład:Bawełna<br /><br />Idealnie dopasowane"; product.Gender = Gender.Woman; product.Group = Group.Spodnie; product.Sizes = size; product.Table = @"\Upload\Tables\92e81a01-5c46-4687-8a53-5aa182821760.jpg"; context.Add(product); //Second product Product product1 = new Product(); List <Size> size1 = new List <Size>(); size1.Add(new Size(SizeOfPruduct.M, 1)); size1.Add(new Size(SizeOfPruduct.L, 1)); size1.Add(new Size(SizeOfPruduct.XL, 1)); size1.Add(new Size(SizeOfPruduct.XXL, 1)); List <Photos> photosList1 = new List <Photos>(); photosList1.Add(new Photos(@"\Upload\Photos\4c44be83-44bd-4e89-b2e9-5ebb2b41eded.jpg")); photosList1.Add(new Photos(@"\Upload\Photos\41efc1cd-a190-4e7b-a7bd-1e51fcd038db.jpg")); photosList1.Add(new Photos(@"\Upload\Photos\87c39856-4d41-494f-beda-a84d3db48857.jpg")); product1.Photos = photosList1; product1.Name = "Marynarka męska"; product1.Price = 299; product1.Description = "Marynarka męska<br />Skład:Bawełna"; product1.Gender = Gender.Men; product1.Group = Group.Kurtki; product1.Sizes = size1; product1.Table = @"\Upload\Tables\92e81a01-5c46-4687-8a53-5aa182821760.jpg"; context.Add(product1); await context.SaveChangesAsync(); } }
public void Test0020() { #region テストデータ準備 var testEntity = TestUtilLib.GenarateRandomTodoTask(); var testEntity1 = new TodoTask().CopyValuesFrom(testEntity); var testEntity2 = new TodoTask().CopyValuesFrom(testEntity); var testEntity3 = new TodoTask().CopyValuesFrom(testEntity); var testEntity4 = new TodoTask().CopyValuesFrom(testEntity); { int i = 1; testEntity1.TodoTaskId = i++.ToString(); testEntity1.StatusCode = StatusCode.CODE_NOT_YET; testEntity2.TodoTaskId = i++.ToString(); testEntity2.StatusCode = StatusCode.CODE_FINISHED; testEntity3.TodoTaskId = i++.ToString(); testEntity3.StatusCode = StatusCode.NAME_NOT_YET; testEntity4.TodoTaskId = i++.ToString(); testEntity4.StatusCode = StatusCode.NAME_FINISHED; } using (var context = new EfDbContext()) { context.Add(testEntity1); context.Add(testEntity2); context.Add(testEntity3); context.Add(testEntity4); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(4, context.TodoTasks.Count()); #endregion IRequest request = new Request(); MainViewSearch logic = new MainViewSearch(); IResponse response = logic.DoProcess(request); var searchResults = ((MainViewSearch.Result)response.Result).TodoTasks; Assert.AreEqual(3, searchResults.Count); { int i = 0; Assert.AreEqual(testEntity1.TodoTaskId, searchResults[i++].TodoTaskId); Assert.AreEqual(testEntity3.TodoTaskId, searchResults[i++].TodoTaskId); Assert.AreEqual(testEntity4.TodoTaskId, searchResults[i++].TodoTaskId); } }
public void Test0030() { #region テストデータ準備 var testEntity1 = TestUtilLib.GenarateRandomTodoTask(); var testEntity2 = TestUtilLib.GenarateRandomTodoTask(); using (var context = new EfDbContext()) { context.Add(testEntity1); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion var dbEntity1 = DalTodoTask.Find(testEntity1.TodoTaskId); var dbEntity2 = DalTodoTask.Find(testEntity2.TodoTaskId); Assert.IsNull(dbEntity2); #region DBから取得したエンティティと値を比較(全て一致するはず) foreach (var property in testEntity1.GetType().GetProperties()) { Assert.AreEqual(property.GetValue(testEntity1), property.GetValue(dbEntity1)); } #endregion }
public async Task <IActionResult> Create([Bind("FirstName,MiddleName,LastName,Phone,DepartmentId,Id")] EmployeeCreateEditViewModel employee) { if (ModelState.IsValid) { var employeeIns = _mapper.Map <EmployeeCreateEditViewModel, Employee>(employee); try { _context.Add(employeeIns); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException dbUpdateException) { _logger.LogError("{ExceptionMessage}", dbUpdateException.Message); ModelState.AddModelError(String.Empty, "Ошибка при сохранении"); //return View(employee); } catch (Exception e) { _logger.LogError("{ExceptionMessage}", e.Message); } } ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", employee.DepartmentId); return(View(employee)); }
public async Task <IActionResult> Create( [Bind( "Name,Code,CountChanel,IsActiv,IsCommunicationDevice,NumberConnectionPoints,Description,CreatedDate,Id")] ModuleType moduleType) { if (ModelState.IsValid) { if (moduleType.IsActiv && !moduleType.IsCommunicationDevice) { var result = _context.ModulesTypes.Any(x => x.IsActiv && !x.IsCommunicationDevice); if (result) { ModelState.AddModelError(string.Empty, "Уже существует действующий модуль LPBS"); return(View(moduleType)); } } if (moduleType.IsCommunicationDevice) { moduleType.NumberConnectionPoints = 0; } _context.Add(moduleType); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(moduleType)); }
public void TestMethod0050() { #region テストデータ準備 var testEntity = TestUtilLib.GenarateRandomTodoTask(); using (var context = new EfDbContext()) { context.Add(testEntity); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion var dialogParameters = new DialogParameters { { nameof(DialogWindowEditViewModel.Parameter), new DialogWindowEditViewModel.Parameter { TodoTask = testEntity, } } }; var vm = new DialogWindowEditViewModel(); vm.OnDialogOpened(dialogParameters); vm.DeleteClick.Execute(); // この画面でレコードが削除される using (var context = new EfDbContext()) Assert.AreEqual(0, context.TodoTasks.Count()); // カバレッジ 100% にするためのコード vm.RequestClose += new Action <IDialogResult>(delegate { }); vm.DeleteClick.Execute(); }
public void TestMethod0050() { #region テストデータ準備 var testEntityOrg = TestUtilLib.GenarateRandomTodoTask(); testEntityOrg.StatusCode = StatusCode.CODE_NOT_YET; using (var context = new EfDbContext()) { context.Add(testEntityOrg); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion var vm = new MainViewModel(new DummyDialogService()); vm.OnNavigatedTo(new Prism.Regions.NavigationContext(null, new Uri("dummy", UriKind.Relative))); #region ボタン〔編集〕押下 ⇒ 編集画面右上[×]ボタン押下で戻る // 編集前、データグリッドにはテストデータの行が存在する Assert.AreEqual(1, vm.DataGridItemsSource.Count); vm.EditClick.Execute(); // 編集前と変わらず、データグリッドにはテストデータの行が存在する Assert.AreEqual(1, vm.DataGridItemsSource.Count); #endregion }
public void AddUser_InputUser_returnFalse() { //b86c0587-5fd7-4df0-9713-1fc213beaad2 //arrange bool succes = true; var user = new User() { UserId = tesUserId, Username = "******", FirstName = "Valera", LastName = "Borow" }; //act try { _service.Add(user); _service.SaveChanges(); } catch (Exception e) { succes = false; Assert.IsFalse(succes, $"{e.Message}"); } //assert Assert.IsFalse(succes, "not valid user"); }
public async Task <dynamic> Post([FromBody] UpdateStatus command) { try { if (ModelState.IsValid) { Status status = _mapper.Map <UpdateStatus, Status>(command); _dbContext.Add(status); int result = await _dbContext.SaveChangesAsync(); // send event StatusReceived message = Mapper.Map <StatusReceived>(command); await _messagePublisher.PublishMessageAsync(message.MessageType, message, "StatusReceived"); //return result return(result > 0 ? new { Saved = true, } : new { Saved = false, }); } return(BadRequest()); } catch (DbUpdateException) { ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public async Task <IActionResult> Create([Bind("Id,Name,Description,IsResponsibleProjectsAndSubProjects,IsResponsibleDesignWork")] Department department) { //IX_Departments_Name if (ModelState.IsValid) { if (_context.Departments.Any(x => String.Equals(x.Name, department.Name))) { ModelState.AddModelError("Name", "Отдел уже существует"); } if (ModelState.IsValid) { try { _context.Add(department); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException e) { var exception = e.InnerException; if (exception != null && exception.Message.Contains("IX_Departments_Name")) { ModelState.AddModelError("Name", "Отдел уже существует"); } } } } return(View(department)); }
public void Given_NoItems_Them_AddNewItem() { var options = new DbContextOptionsBuilder <EfDbContext>() .UseInMemoryDatabase(databaseName: "InMemory_EFDatabaseFirstDB") .Options; var itemSaved = new Item(); //Arrange var expirationDay = DateTime.Now.AddYears(1); //Act using (var context = new EfDbContext(options)) { var newItem = new Item() { Name = "Ron Palido", Description = "Drink", Expiration = expirationDay }; context.Add(newItem); context.SaveChanges(); itemSaved = context.Items.Find(1); } //Assert Assert.IsNotNull(itemSaved, "Failed -Item not saved"); Assert.AreEqual(itemSaved.Name, "Ron Palido", "Failed - Errons in Field Name"); Assert.AreEqual(itemSaved.Description, "Drink", "Failed - Errons in Field Description"); Assert.AreEqual(itemSaved.Expiration, expirationDay, "Failed - Errons in Field expiration"); }
public async Task <IActionResult> Create([Bind("Id,Name,Description")] Contractor contractor) { if (ModelState.IsValid) { if (_context.Statuses.Any(x => String.Equals(x.Name, contractor.Name))) { ModelState.AddModelError("Name", "Уже существует"); } if (ModelState.IsValid) { try { _context.Add(contractor); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException e) { var exception = e.InnerException; if (exception != null && exception.Message.Contains("IX_Contractors_Name")) { ModelState.AddModelError("Name", "Контрагент уже существует"); } } } } return(View(contractor)); }
public void TestMethod0040() { #region テストデータ準備 var testEntity1 = TestUtilLib.GenarateRandomTodoTask(); var testEntity2 = TestUtilLib.GenarateRandomTodoTask(); { testEntity1.StatusCode = StatusCode.CODE_NOT_YET; testEntity2.StatusCode = StatusCode.CODE_FINISHED; } using (var context = new EfDbContext()) { context.Add(testEntity1); context.Add(testEntity2); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(2, context.TodoTasks.Count()); #endregion var vm = new MainViewModel(new DummyDialogService()); vm.OnNavigatedTo(new Prism.Regions.NavigationContext(null, new Uri("dummy", UriKind.Relative))); #region 初期表示の確認 // データグリッドには、ステータス「not yet」のレコードのみが表示されている Assert.AreEqual(1, vm.DataGridItemsSource.Count); Assert.AreEqual(testEntity1.TodoTaskId, vm.DataGridItemsSource[0].TodoTask.TodoTaskId); // 行が未選択状態 ⇒ 行を選択 Assert.IsNull(vm.DataGridSelectedItem.Value); vm.DataGridSelectedItem.Value = vm.DataGridItemsSource[0]; Assert.AreEqual(testEntity1.TodoTaskId, vm.DataGridSelectedItem.Value.TodoTask.TodoTaskId); Assert.AreEqual(StatusCode.NAME_NOT_YET, vm.DataGridSelectedItem.Value.TodoTaskStatusName); #endregion #region ボタン〔完了〕押下 vm.FinishClick.Execute(); // 全てのレコードがステータス「finished」になったので、データグリッドの表示行数もゼロ Assert.AreEqual(0, vm.DataGridItemsSource.Count); #endregion }
public void AddPersone(Persone persone) { if (persone != null) { context.Add(persone); context.SaveChanges(); } }
/// <summary> /// データベースに Setting を登録します /// </summary> public static Setting AddSettingToDb(Setting _setting) { using (var context = new EfDbContext()) { context.Add <Setting>(_setting); context.SaveChanges(); } return(_setting); }
/// <summary> /// データベースに TodoTask を登録します /// </summary> public static TodoTask AddTodoTaskToDb(TodoTask _entity) { using (var context = new EfDbContext()) { context.Add <TodoTask>(_entity); context.SaveChanges(); } return(_entity); }
public async Task AcquireStatus(UpdateStatus command) { Status status = _mapper.Map <UpdateStatus, Status>(command); _dbContext.Add(status); int result = await _dbContext.SaveChangesAsync(); // send event StatusReceived message = Mapper.Map <StatusReceived>(command); await _messagePublisher.PublishMessageAsync(message.MessageType, message, "StatusReceived"); }
public void Test0010() { #region テストデータ準備 var testEntity = TestUtilLib.GenarateRandomTodoTask(); var testEntity1 = new TodoTask().CopyValuesFrom(testEntity); var testEntity2 = new TodoTask().CopyValuesFrom(testEntity); var testEntity3 = new TodoTask().CopyValuesFrom(testEntity); { testEntity1.TodoTaskId = "a"; testEntity1.DueDate = testEntity1.DueDate.Value.AddSeconds(1); testEntity2.TodoTaskId = "c"; testEntity3.TodoTaskId = "b"; } using (var context = new EfDbContext()) { context.Add(testEntity1); context.Add(testEntity2); context.Add(testEntity3); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(3, context.TodoTasks.Count()); #endregion IRequest request = new Request(); MainViewSearch logic = new MainViewSearch(); IResponse response = logic.DoProcess(request); var searchResults = ((MainViewSearch.Result)response.Result).TodoTasks; Assert.AreEqual(3, searchResults.Count); { int i = 0; Assert.AreEqual(testEntity3.TodoTaskId, searchResults[i++].TodoTaskId); Assert.AreEqual(testEntity2.TodoTaskId, searchResults[i++].TodoTaskId); Assert.AreEqual(testEntity1.TodoTaskId, searchResults[i++].TodoTaskId); } }
public void Test0040() { #region テストデータ準備 var testEntityBeforeUpdate = TestUtilLib.GenarateRandomTodoTask(); var testEntityOfUpdate = TestUtilLib.GenarateRandomTodoTask(); testEntityOfUpdate.TodoTaskId = testEntityBeforeUpdate.TodoTaskId; testEntityOfUpdate.DueDate = testEntityBeforeUpdate.DueDate.Value.AddMinutes(1); using (var context = new EfDbContext()) { context.Add(testEntityBeforeUpdate); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion Assert.AreEqual(0, DalTodoTask.Update(new TodoTask { TodoTaskId = null })); Assert.AreEqual(1, DalTodoTask.Update(testEntityOfUpdate)); List <TodoTask> dbEntities; #region データを取得し、結果を確認(全て一致するはず(レコード登録日時、レコード更新日時 は比較除外)) using (var context = new EfDbContext()) dbEntities = context.TodoTasks.ToList(); Assert.AreEqual(1, dbEntities.Count); var dbEntity = dbEntities[0]; foreach (var property in testEntityOfUpdate.GetType().GetProperties()) { switch (property.Name) { case nameof(testEntityOfUpdate.TodoTaskId): Assert.AreEqual(property.GetValue(testEntityBeforeUpdate), property.GetValue(dbEntity)); Assert.AreEqual(property.GetValue(testEntityOfUpdate), property.GetValue(dbEntity)); break; case nameof(testEntityOfUpdate.CreateDateTime): case nameof(testEntityOfUpdate.UpdateDateTime): break; default: Assert.AreNotEqual(property.GetValue(testEntityBeforeUpdate), property.GetValue(dbEntity)); Assert.AreEqual(property.GetValue(testEntityOfUpdate), property.GetValue(dbEntity)); break; } } #endregion }
public async Task <IActionResult> Create( [Bind( "Name,SerialNum,CertifiedNum,ProductTypeId,SubProjectId,IsFormed,ManufacturingDate,ShippedDate,OrderDate,ShippedDate,Id,Description")] ProductCreateViewModel productDto) { if (ModelState.IsValid) { if (_context.Products.Any(x => x.SerialNum == productDto.SerialNum && x.SerialNum != null)) { ModelState.AddModelError("SerialNum", "Серийный номер уже существует"); } if (_context.Products.Any(x => x.CertifiedNum == productDto.CertifiedNum && x.CertifiedNum != null)) { ModelState.AddModelError("CertifiedNum", "Код уже используется"); } if (ModelState.IsValid) { var product = _mapper.Map <ProductCreateViewModel, Product>(productDto); _context.Add(product); try { await _context.SaveChangesAsync(); return(RedirectToAction("GetProductsForSubProject", new { subProjectId = product.SubProjectId })); } catch (DbUpdateException e) { var exception = e.InnerException; if (exception != null && exception.Message.Contains("IX_Products_SerialNum")) { ModelState.AddModelError("SerialNum", "Такой номер уже используется"); } if (exception != null && exception.Message.Contains("IX_Products_CertifiedNum")) { ModelState.AddModelError("CertifiedNum", "Такой номер уже используется"); } } } } ViewData["ProductTypeId"] = new SelectList(_context.ProductTypes, "Id", "Name", productDto.ProductTypeId); // ViewData["SubProjectId"] = // new SelectList(_context.SubProjects, "Id", "Name", productDto.SubProjectId); return(View(productDto)); }
public GoodsItem Add(GoodsItem item) { if (item.Characteristics.HumidityLow > item.Characteristics.HumidityHigh) { throw new ArgumentException("Incorrect humidity"); } if (item.Characteristics.TemperatureLow > item.Characteristics.TemperatureHigh) { throw new ArgumentException("Incorrect temperature"); } _context.Add(item); _context.SaveChanges(); return(item); }
public void TestMethod0060() { #region テストデータ準備 var testEntityOrg = TestUtilLib.GenarateRandomTodoTask(); testEntityOrg.StatusCode = StatusCode.CODE_NOT_YET; using (var context = new EfDbContext()) { context.Add(testEntityOrg); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion #region ロジックの応答を設定 var testEntityUpd = testEntityOrg.CopyValuesFrom(testEntityOrg); testEntityUpd.StatusCode = StatusCode.CODE_FINISHED; var result = new DialogParameters { { nameof(DialogWindowEditViewModel.Result), new DialogWindowEditViewModel.Result { TodoTask = testEntityUpd } } }; #endregion var vm = new MainViewModel(new DummyDialogService()) { TestDialogResult = new DialogResult(ButtonResult.OK), TestDialogParameters = result, }; vm.OnNavigatedTo(new Prism.Regions.NavigationContext(null, new Uri("dummy", UriKind.Relative))); #region ボタン〔編集〕押下 ⇒ 編集画面〔更新〕押下で戻る // 編集前、データグリッドにはテストデータの行が存在する Assert.AreEqual(1, vm.DataGridItemsSource.Count); vm.EditClick.Execute(); // 全てのレコードがステータス「finished」になったので、データグリッドの表示行数もゼロ Assert.AreEqual(0, vm.DataGridItemsSource.Count); #endregion }
public void Verify_QueriesMethods_WorksProperly() { int setCalls = 0; var dbsetMock = new Mock <DbSet <TestEntity> >(); var dbModelMock = new Mock <EfDbModel>(); dbModelMock.Setup(x => x.Set <TestEntity>()).Returns(dbsetMock.Object); Func <string, EfDbModel> createDbContextBehaviour = (cs) => { return(dbModelMock.Object); }; var dbContext = new EfDbContext(createDbContextBehaviour); dbContext.CreateDbContext(); var queryable = dbContext.Query <TestEntity>(); setCalls++; dbModelMock.Verify(x => x.Set <TestEntity>(), Times.Exactly(setCalls)); dbContext.Add(new TestEntity()); setCalls++; dbModelMock.Verify(x => x.Set <TestEntity>(), Times.Exactly(setCalls)); dbsetMock.Verify(x => x.Add(It.IsAny <TestEntity>()), Times.Once()); dbContext.AddRange(new List <TestEntity>()); setCalls++; dbModelMock.Verify(x => x.Set <TestEntity>(), Times.Exactly(setCalls)); dbsetMock.Verify(x => x.AddRange(It.IsAny <List <TestEntity> >()), Times.Once()); dbContext.Remove(new TestEntity()); setCalls++; dbModelMock.Verify(x => x.Set <TestEntity>(), Times.Exactly(setCalls)); dbsetMock.Verify(x => x.Remove(It.IsAny <TestEntity>()), Times.Once()); dbContext.RemoveRange(new List <TestEntity>()); setCalls++; dbModelMock.Verify(x => x.Set <TestEntity>(), Times.Exactly(setCalls)); dbsetMock.Verify(x => x.RemoveRange(It.IsAny <List <TestEntity> >()), Times.Once()); }
public async Task <IActionResult> Create([Bind("Name,ProductSubTypeId,Description,Id")] ProductType productType) { if (ModelState.IsValid) { if (_context.ProductTypes.Any(x => String.Equals(x.Name, productType.Name))) { ModelState.AddModelError("Name", "Такой тип уже существует"); } if (ModelState.IsValid) { _context.Add(productType); try { _context.Add(productType); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException e) { var exception = e.InnerException; if (exception != null && exception.Message.Contains("IX_ProductTypes_Name")) { ModelState.AddModelError("Name", "Тип уже существует"); } } } } ViewData["ProductSubTypeId"] = new SelectList(_context.ProductSubTypes, "Id", "Name", productType.ProductSubTypeId); return(View(productType)); }
public void Given_NoItems_Them_AddNewItem() { var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder <EfDbContext>() .UseSqlite(connection) .Options; var itemSaved = new Item(); //Arrange var expirationDay = DateTime.Now.AddYears(1); // Create the schema in the database using (var context = new EfDbContext(options)) { context.Database.EnsureCreated(); } //Act using (var context = new EfDbContext(options)) { context.Database.EnsureCreated(); var newItem = new Item() { Name = "Ron Palido", Description = "Drink", Expiration = expirationDay }; context.Add(newItem); context.SaveChanges(); itemSaved = context.Items.Find(1); } //Assert Assert.IsNotNull(itemSaved, "Failed -Item not saved"); Assert.AreEqual(itemSaved.Name, "Ron Palido", "Failed - Errons in Field Name"); Assert.AreEqual(itemSaved.Description, "Drink", "Failed - Errons in Field Description"); Assert.AreEqual(itemSaved.Expiration, expirationDay, "Failed - Errons in Field expiration"); }
public void Test0060() { #region テストデータ準備 var testEntityExist = TestUtilLib.GenarateRandomTodoTask(); var testEntityNotExist = TestUtilLib.GenarateRandomTodoTask(); using (var context = new EfDbContext()) { context.Add(testEntityExist); context.SaveChanges(); } using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count()); #endregion Assert.AreEqual(1, DalTodoTask.Delete(testEntityExist.TodoTaskId)); Assert.AreEqual(0, DalTodoTask.Delete(testEntityNotExist.TodoTaskId)); using (var context = new EfDbContext()) Assert.AreEqual(0, context.TodoTasks.Count()); }
private void SaveProject(string projectName) { var existing = _context.Projects.SingleOrDefault(x => x.GlutProjectName == projectName); if (existing == null) { var project = new GlutProject { GlutProjectName = projectName, CreatedDateTimeUtc = _environment.SystemDateTimeUtc, ModifiedDateTimeUtc = _environment.SystemDateTimeUtc, CreatedByUserName = _environment.UserName }; _context.Add(project); } else { existing.ModifiedDateTimeUtc = _environment.SystemDateTimeUtc; _context.Update(existing); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); using (var context = new EfDbContext()) { var Item = new Item() { Name = "Ron Palido", Description = "Drink", Expiration = DateTime.Now.AddYears(1) }; Console.WriteLine($"Item NOT saved -> Id {Item.id} {Item.Name} {Item.Expiration}"); context.Add(Item); context.SaveChanges(); Console.WriteLine($"Item saved -> Id {Item.id} {Item.Name} {Item.Expiration}"); Console.ReadKey(); } }
public UserContract CreateUser(CreateUserContract user) { if (_context.Users.Any(x => string.Equals(x.Email, user.Email))) { throw new ValidationException(System.Net.HttpStatusCode.NoContent, ApiResources.DuplicateEmail); } var newUser = _mapper.Map <CreateUserContract, User>(user); newUser.Password = Security.SecurityHelper.GenerateHash(user.Password); var token = _authenticationService.RequestToken(newUser); newUser.AccessToken = token; newUser.LastLogin = DateTime.UtcNow; var ee = _context.Add(newUser); _context.SaveChanges(); return(_mapper.Map <User, UserContract>(ee.Entity)); }