/********************************************************* #A This method gets a PriceOffer class to send to the user to update #B This loads the book with any existing Promotion #C I return either the existing Promotion for editing, or create a new one. The important point is to set the BookId, as we need to pass that through to the second stage * ******************************************************/ /// <summary> /// This deletes a promotion if the book has one, otherwise is adds a promotion /// </summary> /// <param name="promotion"></param> /// <returns></returns> public ValidationResult AddRemovePriceOffer(PriceOffer promotion) //#A { var book = _context.Books //#B .Include(r => r.Promotion) //#B .Single(k => k.BookId //#B == promotion.BookId); //#B if (book.Promotion != null) //#C { _context.Remove(book.Promotion); //#D _context.SaveChanges(); //#D return(null); //#E } if (string.IsNullOrEmpty(promotion.PromotionalText)) //#F { return(new ValidationResult( //#G "This field cannot be empty", //#G new [] { nameof(PriceOffer.PromotionalText) })); //#G } book.Promotion = promotion; //#H _context.SaveChanges(); //#I return(null); //#J }
public async Task CalculateCorrectSums() { // Arrange Account account = new("Foo1"); Category category = new("abcd"); context.AddRange(new List <Payment> { new Payment(DateTime.Today, 60, PaymentType.Income, account, category: category), new Payment(DateTime.Today, 20, PaymentType.Expense, account, category: category), new Payment(DateTime.Today.AddMonths(-1), 50, PaymentType.Expense, account, category: category), new Payment(DateTime.Today.AddMonths(-2), 40, PaymentType.Expense, account, category: category) }); context.Add(account); context.Add(category); context.SaveChanges(); // Act List <StatisticEntry> result = await new GetCategoryProgressionHandler(contextAdapterMock.Object).Handle( new GetCategoryProgressionQuery(category.Id, DateTime.Today.AddYears(-1), DateTime.Today.AddDays(3)), default); // Assert result[0].Value.Should().Be(40); result[1].Value.Should().Be(-50); result[2].Value.Should().Be(-40); }
public async Task GetValues_CorrectSums() { // Arrange context.AddRange(new List <Payment> { new Payment(DateTime.Today, 60, PaymentType.Income, new Account("Foo1")), new Payment(DateTime.Today, 20, PaymentType.Income, new Account("Foo2")), new Payment(DateTime.Today, 50, PaymentType.Expense, new Account("Foo3")), new Payment(DateTime.Today, 40, PaymentType.Expense, new Account("Foo3")) }); context.SaveChanges(); // Act List <StatisticEntry> result = await new GetCashFlowQueryHandler(contextAdapterMock.Object).Handle(new GetCashFlowQuery { StartDate = DateTime .Today .AddDays(-3), EndDate = DateTime .Today .AddDays(3) }, default); // Assert result[0].Value.ShouldEqual(80); result[1].Value.ShouldEqual(90); result[2].Value.ShouldEqual(-10); }
public void TestWrongWayToSetupRelationshipsOk() { //SETUP var sqlOptions = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(sqlOptions)) { context.Database.EnsureCreated(); //ATTEMPT var book = new Book { Title = "Test", Price = 10m }; context.Add(book); context.SaveChanges(); var review = new Review { BookId = book.BookId, NumStars = 1 }; context.Add(review); context.SaveChanges(); //VERIFY var bookWithReview = context.Books.Include(x => x.Reviews).Single(); bookWithReview.Reviews.Count.ShouldEqual(1); } }
public void TestCreateBookWriteTwiceDisconnectedBad() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); var oneBook = new Book { Title = "test" }; using var context = new EfCoreContext(options); context.Database.EnsureCreated(); context.Add(oneBook); context.SaveChanges(); context.ChangeTracker.Clear(); //ATTEMPT var state1 = context.Entry(oneBook).State; context.Add(oneBook); var state2 = context.Entry(oneBook).State; var ex = Assert.Throws <DbUpdateException>(() => context.SaveChanges()); //VERIFY ex.InnerException.Message.ShouldEqual("SQLite Error 19: 'UNIQUE constraint failed: Books.BookId'."); state1.ShouldEqual(EntityState.Detached); state2.ShouldEqual(EntityState.Added); }
public async Task GetValues_CorrectSums() { // Arrange var testCat1 = new Category("Ausgehen"); var testCat2 = new Category("Rent"); var testCat3 = new Category("Food"); var account = new Account("test"); var paymentList = new List<Payment> { new Payment(DateTime.Today, 60, PaymentType.Income, account, category: testCat1), new Payment(DateTime.Today, 90, PaymentType.Expense, account, category: testCat1), new Payment(DateTime.Today, 10, PaymentType.Expense, account, category: testCat3), new Payment(DateTime.Today, 90, PaymentType.Expense, account, category: testCat2) }; context.Payments.AddRange(paymentList); context.SaveChanges(); // Act List<StatisticEntry> result = (await new GetCategorySpreadingQueryHandler(context).Handle(new GetCategorySpreadingQuery { StartDate = DateTime.Today.AddDays(-3), EndDate = DateTime.Today.AddDays(3) }, default)) .ToList(); // Assert result.Count.ShouldEqual(3); result[0].Value.ShouldEqual(90); result[1].Value.ShouldEqual(30); result[2].Value.ShouldEqual(10); }
public void TestBookListReviewSaveChangesWithAnotherBookTimeOk(int numReviews) { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); var book1 = CreateBookWithListReviews(numReviews); using (new TimeThings(_output, $"ADD1 BookListReview: {numReviews} entries")) context.Add(book1); var book2 = CreateBookWithListReviews(numReviews); using (new TimeThings(_output, $"ADD2 BookListReview: {numReviews} entries")) context.Add(book2); using (new TimeThings(_output, $"Save(real): BookListReview: {numReviews} entries")) { context.SaveChanges(); } using (new TimeThings(_output, $"Save nothing: BookListReview: {numReviews} entries")) { context.SaveChanges(); } }
public void TestCreateBookWithExistingAuthorsOk() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); context.AddRange(new Author { Name = "Author1" }, new Author { Name = "Author2" }); context.SaveChanges(); context.ChangeTracker.Clear(); //ATTEMPT var existingAuthor1 = context.Authors .Single(a => a.Name == "Author1"); var existingAuthor2 = context.Authors .Single(a => a.Name == "Author2"); var newBook = new Book() { Title = "My Book", //... other property settings left out //Set your AuthorsLink property to an empty collection AuthorsLink = new List <BookAuthor>() }; newBook.AuthorsLink.Add(new BookAuthor { Book = newBook, Author = existingAuthor1, Order = 0 }); newBook.AuthorsLink.Add(new BookAuthor { Book = newBook, Author = existingAuthor2, Order = 1 }); context.Add(newBook); context.SaveChanges(); context.ChangeTracker.Clear(); //VERIFY var checkBook = context.Books .Include(book => book.AuthorsLink) .ThenInclude(bookAuthor => bookAuthor.Author) .Single(); checkBook.AuthorsLink.Select(x => x.Author.Name).ShouldEqual(new[] { "Author1", "Author2" }); }
public int Save() { try { return(_context.SaveChanges()); } catch (Exception ex) { throw new Exception(ex.Message); } }
public Book AddReviewToBook(Review review) //#D { var book = _context.Books //#E .Include(r => r.Reviews) //#E .Single(k => k.BookId //#E == review.BookId); //#E book.Reviews.Add(review); //#F _context.SaveChanges(); //#G return(book); //#H }
public void TestUpdateLineItemInOrder() { //SETUP var userId = Guid.NewGuid(); var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options, new FakeUserIdService(userId)); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var orderSetup = new Order { CustomerId = userId, LineItems = new List <LineItem> { new LineItem { BookId = 1, LineNum = 0, BookPrice = 123, NumBooks = 1 } } }; context.Orders.Add(orderSetup); context.SaveChanges(); context.ChangeTracker.Clear(); //ATTEMPT var order = context.Orders.Include(x => x.LineItems).First(); order.LineItems = new List <LineItem> { new LineItem { BookId = 1, LineNum = 0, BookPrice = 456, NumBooks = 1 } }; context.SaveChanges(); //VERIFY context.ChangeTracker.Clear(); var orderCheck = context.Orders.Include(x => x.LineItems).First(); orderCheck.LineItems.First().BookPrice.ShouldEqual(456); }
// Demo public IActionResult AddSingle() { var rand = new Random(); var itemToAdd = new Author { Name = "Hello World " + rand.Next() }; _context.Add(itemToAdd); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public void TestCreateBookWithExistingAuthorSavedToDatabase() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); context.Add(new Author { Name = "Mr. A" }); context.SaveChanges(); //ATTEMPT var foundAuthor = context.Authors //#A .SingleOrDefault(author => author.Name == "Mr. A"); //#A if (foundAuthor == null) //#A { throw new Exception("Author not found"); //#A } var book = new Book //#B { //#B Title = "Test Book", //#B PublishedOn = DateTime.Today //#B }; //#B book.AuthorsLink = new List <BookAuthor> //#C { //#C new BookAuthor //#C { //#C Book = book, //#C Author = foundAuthor //#C } //#C }; //#C context.Add(book); //#D context.SaveChanges(); //#D /************************************************************ #A You reads in the author with a check that the author was found #B This creates a book in the same way as the previous example #C This adds a AuthorBook linking entry, but it uses the Author that is already in the database #D This adds the new book to the DbContext Books property and call SaveChanges * *********************************************************/ //VERIFY context.Books.Count().ShouldEqual(1); //#E context.Authors.Count().ShouldEqual(1); //#F }
public bool Save(Plant plant) { if (plant.Id > 0) { _context.Entry(plant).State = EntityState.Modified; _context.Entry(plant).State = EntityState.Detached; } else { _context.Plants.Add(plant); } var result = _context.SaveChanges(); return(result > 0); }
private async Task CreateRecurringPayments() { var settingsFacade = new SettingsFacade(new SettingsAdapter()); try { Debug.WriteLine("RecurringPayment Job started."); EfCoreContext.DbPath = GetLocalFilePath(); var context = new EfCoreContext(); await new RecurringPaymentAction(new RecurringPaymentDbAccess(context)) .CreatePaymentsUpToRecur() .ConfigureAwait(true); context.SaveChanges(); Debug.WriteLine("RecurringPayment Job finished."); } catch (Exception ex) { Crashes.TrackError(ex); } finally { settingsFacade.LastExecutionTimeStampRecurringPayments = DateTime.Now; } }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); Debug.WriteLine("ClearPayment started"); EfCoreContext.DbPath = DatabaseConstants.DB_NAME; var settingsFacade = new SettingsFacade(new SettingsAdapter()); try { var context = new EfCoreContext(); await new ClearPaymentAction(new ClearPaymentDbAccess(context)) .ClearPayments() .ConfigureAwait(false); context.SaveChanges(); } catch (Exception ex) { Debug.Write(ex); Debug.WriteLine("ClearPaymentTask stopped due to an error."); } finally { settingsFacade.LastExecutionTimeStampClearPayments = DateTime.Now; Debug.WriteLine("ClearPaymentTask finished."); deferral.Complete(); } }
public void TestConnectedUpdateExistingRelationship() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var book = context.Books .Include(p => p.Reviews) .First(p => p.Reviews.Any()); var orgReviews = book.Reviews.Count; //ATTEMPT book.Reviews.Add(new Review { VoterName = "Unit Test", NumStars = 5, }); context.SaveChanges(); //VERIFY var bookAgain = context.Books .Include(p => p.Reviews) .Single(p => p.BookId == book.BookId); bookAgain.Reviews.ShouldNotBeNull(); bookAgain.Reviews.Count.ShouldEqual(orgReviews + 1); }
private async Task CheckRecurringPayments(JobParameters args) { var settingsManager = new SettingsFacade(new SettingsAdapter()); try { Debug.WriteLine("RecurringPayment Job started."); ExecutingPlatform.Current = AppPlatform.Android; var context = new EfCoreContext(); await new RecurringPaymentAction(new RecurringPaymentDbAccess(context)).CreatePaymentsUpToRecur(); context.SaveChanges(); Debug.WriteLine("RecurringPayment Job finished."); JobFinished(args, false); } catch (Exception ex) { Crashes.TrackError(ex); } finally { settingsManager.LastExecutionTimeStampRecurringPayments = DateTime.Now; } }
public void UsingChangeTrackerClear() { //SETUP var options = SqliteInMemory .CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); //#A context.SeedDatabaseFourBooks(); //#A context.ChangeTracker.Clear(); //#B //ATTEMPT var book = context.Books //#C .Include(b => b.Reviews) .OrderBy(b => b.BookId).Last(); //#C book.Reviews.Add(new Review { NumStars = 5 }); //#D context.SaveChanges(); //#E //VERIFY context.ChangeTracker.Clear(); //#B context.Books.Include(b => b.Reviews) //#F .OrderBy(x => x.BookId).Last() //#F .Reviews.Count.ShouldEqual(3); //#F }
public void UsingThreeInstancesOfTheDbcontext() { //SETUP var options = SqliteInMemory //#A .CreateOptions <EfCoreContext>(); //#A options.StopNextDispose(); //#B using (var context = new EfCoreContext(options)) //#C { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //#D } options.StopNextDispose(); //#B using (var context = new EfCoreContext(options)) //#E { //ATTEMPT var book = context.Books //#F .OrderBy(x => x.BookId).Last(); //#F book.Reviews.Add(new Review { NumStars = 5 }); //#G context.SaveChanges(); //#H } using (var context = new EfCoreContext(options)) //#E { //VERIFY context.Books.Include(b => b.Reviews) //#F .OrderBy(x => x.BookId).Last() //#F .Reviews.Count.ShouldEqual(3); //#F } }
public void TestDeletePriceOffer() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var numPromotions = context.PriceOffers.Count(); //ATTEMPT var promotion = context.PriceOffers //#A .First(); //#A context.Remove(promotion); //#B context.SaveChanges(); //#C /********************************************************** #A I find the first PriceOffer #B I then remove that PriceOffer from the application's DbContext. The DbContext works what to remove based on its type of its parameter #C The SaveChanges calls DetectChanges which finds a tracked PriceOffer entity which is marked as deleted. It then deletes it from the database * *******************************************************/ //VERIFY context.PriceOffers.Count().ShouldEqual(numPromotions - 1); } }
public void TestBookWithRelatedLinks() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var book = context.Books .Include(p => p.Promotion) //#A .Include(p => p.Reviews) //#A .Include(p => p.AuthorsLink) //#A .Single(p => p.Title //#B == "Quantum Networking"); //#B context.Books.Remove(book); //#C context.SaveChanges(); //#D /********************************************************** #A The three Includes make sure that the three dependent relationships are loaded with the Book #B This finds the "Quantum Networking" book, which I know has a promotion, 2 reviews and one BookAuthor link #B I then delete that book #C The SaveChanges calls DetectChanges which finds a tracked Book entity which is marked as deleted. It then deletes its dependent relationships and then deletes the book * *******************************************************/ //VERIFY context.Books.Count().ShouldEqual(3); context.PriceOffers.Count().ShouldEqual(0); //Quantum Networking is the only book with a priceOffer and reviews context.Set <Review>().Count().ShouldEqual(0); context.Set <BookAuthor>().Count().ShouldEqual(3); //three books left, each with a one author } }
public void TestBookWithRelatedLinksWithoutIncludes() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); //ATTEMPT var book = context.Books .Single(p => p.Title == "Quantum Networking"); context.Books.Remove(book); context.SaveChanges(); //VERIFY context.Books.Count().ShouldEqual(3); context.PriceOffers.Count().ShouldEqual(0); //Quantum Networking is the only book with a priceOffer and reviews context.Set <Review>().Count().ShouldEqual(0); context.Set <BookAuthor>().Count().ShouldEqual(3); //three books left, each with a one author } }
public void TestBookListReviewQueryTimeOk(int numReviews) { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); context.Add(CreateBookWithListReviews(numReviews)); context.SaveChanges(); context.ChangeTracker.Clear(); using (new TimeThings(_output, $"1: BookList: {numReviews} entries")) { var book = context.Books .Include(x => x.Reviews) .Single(); book.Reviews.Count.ShouldEqual(numReviews); } using (new TimeThings(_output, $"2: BookList: {numReviews} entries")) { var book = context.Books .Include(x => x.Reviews) .Single(); book.Reviews.Count.ShouldEqual(numReviews); } }
public void TestDeletePriceOfferWithLogging() { //SETUP var showLog = false; var options = SqliteInMemory.CreateOptionsWithLogging <EfCoreContext>(log => { if (showLog) { _output.WriteLine(log.DecodeMessage()); } }); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); var numPromotions = context.PriceOffers.Count(); //ATTEMPT showLog = true; var promotion = context.PriceOffers //#A .First(); //#A context.PriceOffers.Remove(promotion); //#B context.SaveChanges(); //#C showLog = false; //VERIFY context.PriceOffers.Count().ShouldEqual(numPromotions - 1); } }
public void TestAddReviewToBookOk() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); } using (var context = new EfCoreContext(options)) { var service = new AddReviewService(context); //ATTEMPT var dto = service.GetOriginal(1); dto.NumStars = 2; service.AddReviewToBook(dto); context.SaveChanges(); //VERIFY context.Set <Review>().Count().ShouldEqual(3); context.Books.Include(x => x.Reviews).Single(x => x.BookId == 1).Reviews.Single().NumStars.ShouldEqual(2); } }
public void INCORRECTtestOfDisconnectedState() { //SETUP var options = SqliteInMemory .CreateOptions <EfCoreContext>(); using var context = new EfCoreContext(options); context.Database.EnsureCreated(); //#A context.SeedDatabaseFourBooks(); //#A //ATTEMPT var book = context.Books //#B .OrderBy(x => x.BookId).Last(); //#B book.Reviews.Add(new Review { NumStars = 5 }); //#C context.SaveChanges(); //#D //VERIFY //THIS IS INCORRECT!!!!! context.Books //#E .OrderBy(x => x.BookId).Last() //#E .Reviews.Count.ShouldEqual(3); //#E }
public void TestAddPromotionBookOk() { //SETUP var options = SqliteInMemory.CreateOptions <EfCoreContext>(); using (var context = new EfCoreContext(options)) { context.Database.EnsureCreated(); context.SeedDatabaseFourBooks(); } using (var context = new EfCoreContext(options)) { var service = new AddRemovePromotionService(context); //ATTEMPT var dto = service.GetOriginal(1); dto.ActualPrice = dto.OrgPrice / 2; dto.PromotionalText = "Half price today!"; var book = service.AddPromotion(dto); context.SaveChanges(); //VERIFY service.IsValid.ShouldBeTrue(); book.ActualPrice.ShouldEqual(book.OrgPrice / 2); } }
public void UpdatePublicationDateWithLogging() { //SETUP var options = this.NewMethodUniqueDatabaseSeeded4Books(); //#A using (var context = new EfCoreContext(options)) { //REMOVE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! var logIt = new LogDbContext(context); //ATTEMPT var book = context.Books //#B .Single(p => p.Title == "Quantum Networking"); //#B book.PublishedOn = new DateTime(2058, 1, 1); //#C context.SaveChanges(); //#D //VERIFY var bookAgain = context.Books //#E .Single(p => p.Title == "Quantum Networking"); //#E bookAgain.PublishedOn //#F .ShouldEqual(new DateTime(2058, 1, 1)); //#F //REMOVE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
private void RunHandCodedAddReview(EfCoreContext context) { var book = context.Find <Book>(1); book.AddReview(5, "comment", "user", context); context.SaveChanges(); }