public void TestPerformanceCreateDirectViaCtor() { //SETUP var options = SqliteInMemory.CreateOptions<TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); var utData = context.SetupEntitiesDirect(); var service = new CrudServices<TestDbContext>(context, utData.ConfigAndMapper); using (new TimeThings(_output, "RunHandCoded Create", 1)) { context.Add(new DddCtorEntity( 1, "hello")); context.SaveChanges(); } using (new TimeThings(_output, "RunGenericService Create", 1)) { service.CreateAndSave(new DddCtorEntity( 1, "hello")); } } using (var context = new TestDbContext(options)) { context.WipeAllDataFromDatabase(); var utData = context.SetupEntitiesDirect(); var service = new CrudServices<TestDbContext>(context, utData.ConfigAndMapper); using (new TimeThings(_output, "RunGenericService Create", 100)) { for (int i = 0; i < 100; i++) { service.CreateAndSave(new DddCtorEntity(1, "hello")); } } } using (var context = new TestDbContext(options)) { context.WipeAllDataFromDatabase(); using (new TimeThings(_output, "RunHandCoded Create", 100)) { for (int i = 0; i < 100; i++) { context.Add(new DddCtorEntity(1, "hello")); context.SaveChanges(); } } } }
public DatabaeTests() { //Arrange var factory = new ConnectionFactory(); //Get the instance of BlogDBContext context = factory.CreateContextForInMemory(); return; var c = new List <User>(); int documentIndex = 1; for (int i = 1; i < 101; i++) { User user = new User() { Id = i, FirstName = $"FirstName {i}", LastName = $"LastName {i}", AnualSalary = i, Phone = i.ToString(), Documents = new List <Document>(), Parent = i > 1 ? context.Users.Where(x => x.Id == i - 1).First() : null }; context.Add(user); context.SaveChanges(); for (var j = 1; j < 10; j++) { Document d = new Document() { Name = $"Document {documentIndex}", Id = documentIndex, Owner = user }; context.Documents.Add(d); context.SaveChanges(); user.Documents.Append(d); documentIndex++; } context.SaveChanges(); //Console.WriteLine(user.Documents.Count()); //user.PrincipalDocument = user.Documents.First(); //user.Documents = null; //context.Users.Add(user); //context.SaveChanges(); } context.SaveChanges(); users = context.Users; }
public async Task <BizDataOut> BizActionAsync(BizDataIn inputData) { //Put it here so that if SaveChanges is called it will be in database _context.Add(new LogEntry(inputData.Num.ToString())); if (inputData.Num >= 0) { Message = "All Ok"; } else { AddError("Error"); } return(new BizDataOut(inputData.Num.ToString())); }
public void CanCascade_UnmodifiedDifferentType() { using var dbContext = new TestDbContext(); var subject = CreateSubject(); var entity = new TestModel { Property1 = 1 }; dbContext.Add(entity); var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added); var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor); Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result); }
public ListTable Save(ListTable ListTable) { using (TestDbContext _context = new TestDbContext()) { if (ListTable.listTableId == 0) { _context.Add(ListTable); } else { _context.Update(ListTable); } _context.SaveChanges(); return(ListTable); } }
public Trade Save(Trade trade) { using (TestDbContext _context = new TestDbContext()) { if (trade.tradeId == 0) { _context.Add(trade); } else { _context.Update(trade); } _context.SaveChanges(); return(trade); } }
public Level Save(Level level) { using (TestDbContext _context = new TestDbContext()) { if (level.levelId == 0) { _context.Add(level); } else { _context.Update(level); } _context.SaveChanges(); return(level); } }
public async Task <IActionResult> Create([Bind("Id,age,weight")] Bmi bmi) { if (ModelState.IsValid) { Bmi bmi1 = bmi; bmi.bmi = bmi1.age * bmi1.weight / 1000; _context.Add(bmi); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(bmi)); }
public void DiscoverChanges_MultipleCalls_ReturnsDeltaOfChanges() { using var dbContext = new TestDbContext(); var subject = new CascadingTriggerContextDiscoveryStrategy("test", false); var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy()); triggerContextTracker.DiscoverChanges().Count(); var initialContextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger <object>()).ToList(); dbContext.Add(new TestModel { }); var contextDescriptors = subject.Discover(new(false, 100), triggerContextTracker, new NullLogger <object>()).ToList(); Assert.NotEqual(initialContextDescriptors, contextDescriptors); }
public void TestAddLogEntryOk() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); //ATTEMPT context.Add(new LogEntry("Hello")); context.SaveChanges(); //VERIFY context.LogEntries.Count().ShouldEqual(1); } }
public async Task <IActionResult> Create(int id, UserRoleViewModel user_roles) { UserRoleViewModel UserRoles = new UserRoleViewModel(); UserRoles.Roles = (from r in _context.sys_role select new RoleSelect { role_id = r.id, //role_no = r.role_no, role_name = r.rolename, Selected = false }).ToList(); if (ModelState.IsValid) { var password_hash = PasswordHash(user_roles.User.password); user_roles.User.password = password_hash; _context.Add(user_roles.User); await _context.SaveChangesAsync(); List <sys_user_role> user_role_list = new List <sys_user_role>(); var roles = user_roles.Roles; if (roles.Count() > 0) { foreach (var item in roles) { if (item.Selected == true) { user_role_list.Add( new sys_user_role() { sys_user_id = user_roles.User.id, sys_role_id = item.role_id } ); } } } _context.AddRange(user_role_list); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(UserRoles)); }
public async Task TestDeleteWithActionAsyncWithQueryFilterOk() { async Task <IStatusGeneric> DelHandlerAsync(DbContext context, SoftDelEntity entity) { var status = new StatusGenericHandler(); if (!entity.SoftDeleted) { status.AddError("Can't delete if not already soft deleted."); } return(status); } //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); var author = new SoftDelEntity { SoftDeleted = true }; context.Add(author); context.SaveChanges(); } using (var context = new TestDbContext(options)) { var utData = context.SetupEntitiesDirect(); var service = new CrudServicesAsync(context, utData.ConfigAndMapper); context.SoftDelEntities.Count().ShouldEqual(0); context.SoftDelEntities.IgnoreQueryFilters().Count().ShouldEqual(1); //ATTEMPT await service.DeleteWithActionAndSaveAsync <SoftDelEntity>(DelHandlerAsync, 1); //VERIFY service.IsValid.ShouldBeTrue(service.GetAllErrors()); service.Message.ShouldEqual("Successfully deleted a Soft Del Entity"); } using (var context = new TestDbContext(options)) { context.SoftDelEntities.IgnoreQueryFilters().Count().ShouldEqual(0); } }
public async void GivenModelId_RepositoryFindsEntity() { TestDbContext.Database.EnsureDeleted(); // Arrange var wordId = RandomNumber.Next(); var word = new Word().Fake(wordId); TestDbContext.Add(word); TestDbContext.SaveChanges(); // Act var found = await new GenericRepository <Word>(TestDbContext).FindByIdAsync(wordId).ConfigureAwait(false); // Assert Assert.NotNull(found); Assert.Equal(wordId, found.Id); }
public void DiscoverChanges_MultipleCalls_ReturnsSameResult() { using var dbContext = new TestDbContext(); var subject = new NonRecursiveTriggerContextDiscoveryStrategy("test"); var triggerContextTracker = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeRecursionStrategy()); triggerContextTracker.DiscoverChanges().Count(); var initialContextDescriptors = subject.Discover(new TriggerOptions { }, triggerContextTracker, new NullLogger <object>()).ToList(); dbContext.Add(new TestModel { }); var contextDescriptors = subject.Discover(new TriggerOptions { }, triggerContextTracker, new NullLogger <object>()).ToList(); Assert.Equal(initialContextDescriptors, contextDescriptors); }
public void TestAddLogEntryValidationError() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); //ATTEMPT context.Add(new LogEntry("!")); var errors = context.SaveChangesWithValidation(); //VERIFY context.LogEntries.Count().ShouldEqual(0); errors.Any().ShouldBeTrue(); } }
public void UnmodifiedEntity_WhenTypeModified_HoldsUnmodifiedStateAfterSaveChanges() { using var dbContext = new TestDbContext(); var sample1 = new TestModel { Name = "test1" }; dbContext.Add(sample1); dbContext.SaveChanges(); var subject = new TriggerContext <TestModel>(dbContext.Entry(sample1).Entity, dbContext.Entry(sample1).OriginalValues.Clone(), ChangeType.Modified, new()); sample1.Name = "test2"; dbContext.SaveChanges(); Assert.NotNull(subject.UnmodifiedEntity); Assert.Equal("test1", subject.UnmodifiedEntity.Name); }
public void TestDeleteWithActionWithQueryFilterError() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); var author = new SoftDelEntity { SoftDeleted = false }; context.Add(author); context.SaveChanges(); } using (var context = new TestDbContext(options)) { var utData = context.SetupEntitiesDirect(); var service = new CrudServices(context, utData.ConfigAndMapper); context.SoftDelEntities.Count().ShouldEqual(1); context.SoftDelEntities.IgnoreQueryFilters().Count().ShouldEqual(1); //ATTEMPT service.DeleteWithActionAndSave <SoftDelEntity>((dbContext, entity) => { var status = new StatusGenericHandler(); if (!entity.SoftDeleted) { status.AddError("Can't delete if not already soft deleted."); } return(status); }, 1); //VERIFY service.IsValid.ShouldBeFalse(); service.GetAllErrors().ShouldEqual("Can't delete if not already soft deleted."); } using (var context = new TestDbContext(options)) { context.SoftDelEntities.IgnoreQueryFilters().Count().ShouldEqual(1); } }
public void Roundtrip_IsPossible() { Guid oneKey = GuidBuilder.Build(1), twoKey = GuidBuilder.Build(2); using (var ctx = new TestDbContext(_dbFile)) { ctx .Add(id: oneKey, number: 1, text: "uno", monetaryQuantity: 11.1m.Dkk()) .Add(id: twoKey, number: 2, text: "dos", monetaryQuantity: 22.222m.Eur()); ctx.SaveChanges(); } using (var ctx = new TestDbContext(_dbFile)) { TestEntity one = ctx.Entities.SingleOrDefault(e => e.Id == oneKey); Assert.That(one, Is.Not.Null); Assert.That(one, Must.Match.Expected(new { Number = 1, Quantity = new { Amount = 11.1m, Currency = CurrencyIsoCode.DKK.AlphabeticCode() } })); TestEntity two = ctx.Entities.SingleOrDefault(e => e.Id == twoKey); Assert.That(two, Is.Not.Null); Assert.That(two, Must.Match.Expected(new { Number = 2, Quantity = new { Amount = 22.222m, Currency = CurrencyIsoCode.EUR.AlphabeticCode() } })); } }
public async Task Logical_Deletion_ById() { try { Guid?id = null; using (var ctx = new TestDbContext()) { var entity = new WebSite { Url = "http://dotnet.microsoft.com/" }; ctx.Add(entity); await ctx.SaveChangesAsync().ConfigureAwait(false); id = entity.Id; } using (var ctx = new TestDbContext()) { var webSites = ctx.Set <WebSite>().ToList(); webSites.Count().Should().Be(1); webSites.Count(w => w.Deleted).Should().Be(0); } using (var adapater = GetRepository()) { var entity = new TestDbContext().Set <WebSite>().FirstOrDefault(); entity.Should().NotBeNull(); adapater.MarkIdForDelete <WebSite>(id); await adapater.SaveAsync().ConfigureAwait(false); } using (var ctx = new TestDbContext()) { var webSites = ctx.Set <WebSite>().ToList(); webSites.Count().Should().Be(1); webSites.Count(w => w.Deleted).Should().Be(1); webSites[0].DeletionDate.Should().BeSameDateAs(DateTime.Today); } } finally { DeleteAll(); } }
public async Task UpdateFieldsAsync_WithProperties_ShouldOnlyUpdateSpecifiedEntityProperties() { // Arrange var testEntity = new TestEntity { Id = Guid.NewGuid(), Name = "Anakin Skywalker", Number = 1 }; DbContextOptions <TestDbContext> options = new DbContextOptionsBuilder <TestDbContext>() .UseInMemoryDatabase(databaseName: "InMemory_TestDb") .Options; using (var dbContext = new TestDbContext(options)) { dbContext.Add(testEntity); await dbContext.SaveChangesAsync(); } testEntity.Name = "Obi-Wan Kenobi"; testEntity.Number = 2; // Act using (var dbContext = new TestDbContext(options)) { var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContext); await repository.UpdateFieldsAsync(testEntity, te => te.Name); } // Assert using (var dbContext = new TestDbContext(options)) { var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContext); TestEntity updatedTestEntity = await repository.GetByIdAsync(testEntity.Id); updatedTestEntity.Name.Should().Be("Obi-Wan Kenobi"); updatedTestEntity.Number.Should().Be(1); } }
public async Task DeleteAsync_OneGenericVersion_Success_Should_AddEntityWithDeletedState() { const int expCount = 1; var aggregateRoot = new TestAggregateRoot("testing"); _Context.Add(aggregateRoot); await _Context.SaveChangesAsync(); _Context.ChangeTracker.Clear(); IRepositoryAsync <TestAggregateRoot> repository = new TestAggregateRootRepository1(_Context); var entry = await repository.DeleteAsync(new object[] { aggregateRoot.Id }); entry.Should().NotBeNull(); _Context.ChangeTracker.Entries <TestAggregateRoot>() .Should().HaveCount(expCount); _Context.ChangeTracker.Entries <TestAggregateRoot>() .Should().Contain(e => e.Entity.Id == aggregateRoot.Id && e.State == EntityState.Deleted); }
public async Task UpdateFieldsAsync_WithProperties_ShouldUpdateEntityProperties() { // Arrange var testEntity = new TestEntity { Id = Guid.NewGuid(), Name = "Chewbacca", Number = 1 }; DbContextOptions <TestDbContext> options = new DbContextOptionsBuilder <TestDbContext>() .UseInMemoryDatabase(databaseName: "InMemory_TestDb") .Options; using (var dbContext = new TestDbContext(options)) { dbContext.Add(testEntity); await dbContext.SaveChangesAsync(); } TestEntity updatedTestEntity = null; testEntity.Name = "R2-D2"; testEntity.Number = 2; // Act using (var dbContext = new TestDbContext(options)) { var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContext); await repository.UpdateFieldsAsync(testEntity, te => te.Name, te => te.Number); // Assert updatedTestEntity = await repository.GetByIdAsync(testEntity.Id); } // Assert updatedTestEntity.Name.Should().Be("R2-D2"); updatedTestEntity.Number.Should().Be(2); }
public async Task <IActionResult> Create(Customer customer) { //Ben istersem IValidator interface'ni kullanarak kontrol işlemlerini yapabilirim. var result = _customerValidator.Validate(customer); if (result.IsValid) { _context.Add(customer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } //if (ModelState.IsValid) //{ // _context.Add(customer); // await _context.SaveChangesAsync(); // return RedirectToAction(nameof(Index)); //} return(View(customer)); }
public void TestNoBeforeSaveChangesMethodProvided() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); //ATTEMPT context.Add(new UniqueEntity { UniqueString = "bad word" }); var status = context.SaveChangesWithValidation(); //VERIFY status.HasErrors.ShouldBeFalse(status.GetAllErrors()); } using (var context = new TestDbContext(options)) { context.UniqueEntities.Count().ShouldEqual(1); } }
public async void Delete_Non_Existing_Device_Throws_Error() { builder.UseInMemoryDatabase("Delete_Non_Existing_Device_Throws_Error"); var options = builder.Options; Domain.Device device = new Domain.Device(); using (var context = new TestDbContext(options)) { var repository = new DeviceRepository(context); device = new Domain.Device() { Id = 1, Vendor = "V1", Status = true, UId = 1, DateCreated = DateTime.Today }; context.Add(device); context.SaveChanges(); device.Id = 2; await Assert.ThrowsAsync <InvalidOperationException>(async() => await repository.Delete(device)); } }
public async Task <IActionResult> Create(User model) { if (ModelState.IsValid) { var user = new User() { FullName = model.FullName, Email = model.Email, PhoneNumber = model.PhoneNumber, Password = model.Password, ConfirmPassword = model.ConfirmPassword, WardId = model.WardId, DistrictId = model.DistrictId, ProvinceId = model.ProvinceId, Address = model.Address }; testDbContext.Add(user); await testDbContext.SaveChangesAsync(); return(RedirectToAction("ShowUser")); } return(RedirectToAction("Index")); }
public async Task <IActionResult> Create([Bind("UserName")] TbUserPhoto tbUserPhoto, IFormFile Fotografi) { if (ModelState.IsValid) { //....................................................... byte[] imageData = null; if (Fotografi != null) { using (var binary = new BinaryReader(Fotografi.OpenReadStream())) { imageData = binary.ReadBytes((Int32)Fotografi.Length); } } //....................................................... tbUserPhoto.UserPhoto = imageData; //....................................................... _context.Add(tbUserPhoto); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(tbUserPhoto)); }
public async Task TestCrateWithValidationAsyncOk() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); var entity = new NormalEntity { MyInt = 1 }; //ATTEMPT context.Add(entity); await context.SaveChangesWithValidationAsync(); } using (var context = new TestDbContext(options)) { //VERIFY context.NormalEntities.Count().ShouldEqual(1); context.NormalEntities.Single().MyInt.ShouldEqual(1); } }
public async Task TestDbQueryReadManyViaDtoOk() { //SETUP var options = SqliteInMemory.CreateOptions <TestDbContext>(); using (var context = new TestDbContext(options)) { context.Database.EnsureCreated(); #if NETCOREAPP3_0 context.ExecuteScriptFileInTransaction(TestData.GetFilePath("ReplaceTableWithView.sql")); #endif context.Add(new Parent { Children = new List <Child> { new Child { MyString = "Hello" }, new Child { MyString = "Goodbye" } } }); context.SaveChanges(); } using (var context = new TestDbContext(options)) { var utData = context.SetupSingleDtoAndEntities <ChildDbQueryDto>(); var service = new CrudServicesAsync(context, utData.ConfigAndMapper); //ATTEMPT var entities = await service.ReadManyNoTracked <ChildDbQueryDto>().ToListAsync(); //VERIFY service.IsValid.ShouldBeTrue(service.GetAllErrors()); entities.Count.ShouldEqual(2); } }
public async void Get_Device_Returns_Element_If_Exists() { builder.UseInMemoryDatabase("Get_Device_Returns_Element_If_Exists"); var options = builder.Options; var device = new Domain.Device() { Id = 1, Vendor = "V1", Status = true, UId = 1, DateCreated = DateTime.Today }; using (var context = new TestDbContext(options)) { context.Add(device); context.SaveChanges(); } Domain.Device existingDevice = null; Domain.Device nonExistingDevice = null; using (var context = new TestDbContext(options)) { var repository = new DeviceRepository(context); existingDevice = await repository.Get(1); nonExistingDevice = await repository.Get(2); } Assert.True(existingDevice != null && nonExistingDevice == null); Assert.True(existingDevice.Id == device.Id && existingDevice.Vendor == device.Vendor && existingDevice.UId == device.UId && existingDevice.Status == device.Status && existingDevice.DateCreated == device.DateCreated); }