public async Task TestSaveChangesAsyncAddNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                nameof(TestSqlSaveChanges));


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    await noSqlContext.Database.EnsureCreatedAsync();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.SingleOrDefault(p => p.BookId == book.BookId);
                    noSqlBook.ShouldNotBeNull();
                    noSqlBook.AuthorsOrdered.ShouldEqual("Author1, Author2");
                    noSqlBook.ReviewsCount.ShouldEqual(2);
                }
        }
        public async Task TestCosmosDbAzureCosmosDbOk()
        {
            //SETUP
            var config = new ConfigurationBuilder()
                         .AddUserSecrets <Startup>()
                         .Build();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["CosmosUrl"],
                config["CosmosKey"],
                GetType().Name);

            using (var context = new NoSqlDbContext(builder.Options))
            {
                await context.Database.EnsureCreatedAsync();

                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                await context.SaveChangesAsync();

                //VERIFY
                context.Books.Find(book.BookId).ShouldNotBeNull();
            }
        }
        public void TestSaveChangesSoftDeleteNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                nameof(TestSqlSaveChanges));


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    sqlContext.SaveChanges();

                    //ATTEMPT
                    book.SoftDeleted = true;
                    sqlContext.SaveChanges();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                    sqlContext.Books.IgnoreQueryFilters().Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.SingleOrDefault(p => p.BookId == book.BookId);
                    noSqlBook.ShouldBeNull();
                }
        }
        public async Task TestPageOk(int pageSize, int pageNum)  //pageNum starts at 1
        {
            //SETUP
            pageSize.ShouldBeInRange(1, 1000);
            using (var context = new NoSqlDbContext(_options))
            {
                var service = new ListNoSqlBooksService(context);

                //ATTEMPT
                var filterPageOptions = new NoSqlSortFilterPageOptions
                {
                    OrderByOptions = OrderByOptions.ByPriceLowestFirst,
                    PageSize       = pageSize,
                    PageNum        = pageNum
                };
                var temp = await service.SortFilterPageAsync(filterPageOptions); //to set the PrevCheckState

                filterPageOptions.PageNum = pageNum;
                var books = await service.SortFilterPageAsync(filterPageOptions);

                //VERIFY
                books.Count.ShouldEqual(Math.Min(pageSize, books.Count));
                books.First().ActualPrice.ShouldEqual(1 + pageSize * (pageNum - 1));
            }
        }
        public void TestSaveChangesUpdatesNoSqlFail()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASENAME");


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    var ex = Assert.Throws <WebException>(() => sqlContext.SaveChanges());

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                }
        }
Example #6
0
        public async Task <IActionResult> Books(int totalBooksNeeded, bool wipeDatabase, CancellationToken cancellationToken,
                                                [FromServices] SqlDbContext sqlContext,
                                                [FromServices] BookGenerator generator,
                                                [FromServices] IWebHostEnvironment env)
        {
            if (totalBooksNeeded == 0)
            {
                return(View((object)"Error: should contain the number of books to generate."));
            }

            NoSqlDbContext noSqlContext = (NoSqlDbContext)HttpContext.RequestServices.GetService(typeof(NoSqlDbContext));

            if (wipeDatabase)
            {
                sqlContext.DevelopmentWipeCreated(noSqlContext);
            }

            var filepath = Path.Combine(env.WebRootPath, SetupHelpers.SeedFileSubDirectory,
                                        SetupHelpers.TemplateFileName);
            await generator.WriteBooksAsync(filepath, totalBooksNeeded, true, cancellationToken);

            SetupTraceInfo();

            return
                (View((object)((cancellationToken.IsCancellationRequested ? "Cancelled" : "Successful") +
                               $" generate. Num books in database = {sqlContext.Books.Count()}.")));
        }
        public async Task TestSaveChangesAsyncUpdatesNoSqlFail()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASENAME");


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var ex = await Assert.ThrowsAsync <CosmosException>(async() => await sqlContext.SaveChangesAsync());

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                    ex.Message.ShouldStartWith("Response status code does not indicate success: 404 Substatus:");
                }
        }
        public async Task TestNoSqlBookUpdaterOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using var sqlContext   = new SqlDbContext(_sqlOptions);
            using var noSqlContext = new NoSqlDbContext(builder.Options);

            await sqlContext.Database.EnsureCreatedAsync();

            await noSqlContext.Database.EnsureCreatedAsync();

            var updater = new NoSqlBookUpdater(noSqlContext);

            //ATTEMPT
            var book = DddEfTestData.CreateDummyBookOneAuthor();

            sqlContext.Add(book);
            var numBooksChanged = updater.FindNumBooksChanged(sqlContext);
            await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, numBooksChanged,
                                                                              () => sqlContext.SaveChangesAsync());

            //VERIFY
            numBooksChanged.ShouldEqual(1);
            sqlContext.Books.Count().ShouldEqual(1);
            noSqlContext.Books.Find(book.BookId).ShouldNotBeNull();
        }
        public async Task TestWriteBooksAsyncCorrectAmountOk(int numBooks)
        {
            //SETUP
            var noSqlOptions = this.GetCosmosDbToEmulatorOptions <NoSqlDbContext>();
            var sqlOptions   = SqliteInMemory.CreateOptions <SqlDbContext>();

            using (var noSqlContext = new NoSqlDbContext(noSqlOptions))
                using (var sqlContext = new SqlDbContext(sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    await noSqlContext.Database.EnsureDeletedAsync();

                    await noSqlContext.Database.EnsureCreatedAsync();

                    var filepath = TestData.GetFilePath("10ManningBooks.json");

                    var generator = new BookGenerator(sqlOptions, noSqlOptions);

                    //ATTEMPT
                    await generator.WriteBooksAsync(filepath, numBooks, true, default(CancellationToken));

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(numBooks);
                    noSqlContext.Books.Select(_ => 1).AsEnumerable().Count().ShouldEqual(numBooks);
                }
        }
        public async Task TestNoSqlBookUpdaterOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                nameof(TestNoSqlBookUpdaterAsync));


            using (var sqlContext = new SqlDbContext(_sqlOptions))
                using (var noSqlContext = new NoSqlDbContext(builder.Options))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    await noSqlContext.Database.EnsureCreatedAsync();

                    var updater = new NoSqlBookUpdater(noSqlContext);

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var hasUpdates = updater.FindBookChangesToProjectToNoSql(sqlContext);
                    await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, () => sqlContext.SaveChangesAsync());

                    //VERIFY
                    hasUpdates.ShouldBeTrue();
                    sqlContext.Books.Count().ShouldEqual(1);
                    (await noSqlContext.Books.CountAsync(p => p.BookId == book.BookId)).ShouldEqual(1);
                }
        }
        public async Task TestNoSqlBookUpdaterFail_NoBookAddedToSqlDatabase()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATASBASENAME");


            using (var sqlContext = new SqlDbContext(_sqlOptions))
                using (var noSqlContext = new NoSqlDbContext(builder.Options))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    var updater = new NoSqlBookUpdater(noSqlContext);

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var numBooksChanged = updater.FindNumBooksChanged(sqlContext);
                    var ex = await Assert.ThrowsAsync <CosmosException>(async() =>
                                                                        await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, numBooksChanged,
                                                                                                                                          () => sqlContext.SaveChangesAsync()));

                    //VERIFY
                    ex.Message.ShouldStartWith("Response status code does not indicate success: 404 Substatus:");
                    numBooksChanged.ShouldEqual(1);
                    sqlContext.Books.Count().ShouldEqual(0);
                }
        }
        public async Task TestCosmosDbAzureCosmosDbOk()
        {
            //SETUP
            var config = new ConfigurationBuilder()
                         .AddUserSecrets <Startup>()
                         .Build();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["CosmosUrl"],
                config["CosmosKey"],
                nameof(TestNoSqlDbContext));

            using (var context = new NoSqlDbContext(builder.Options))
            {
                await context.Database.EnsureCreatedAsync();

                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                await context.SaveChangesAsync();

                //VERIFY
                (await context.Books.CountAsync(p => p.BookId == book.BookId)).ShouldEqual(1);
            }
        }
        public async Task TestSaveChangesDeleteNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    await sqlContext.SaveChangesAsync();

                    //ATTEMPT
                    sqlContext.Remove(book);
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                    var noSqlBook = noSqlContext.Books.SingleOrDefault(p => p.BookId == book.BookId);
                    noSqlBook.ShouldBeNull();
                }
        }
        public async Task TestNoSqlBookUpdaterFail_NoBookAddedToSqlDatabase()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATASBASENAME");


            using (var sqlContext = new SqlDbContext(_sqlOptions))
                using (var noSqlContext = new NoSqlDbContext(builder.Options))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    var updater = new NoSqlBookUpdater(noSqlContext);

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var hasUpdates = updater.FindBookChangesToProjectToNoSql(sqlContext);
                    var ex         = await Assert.ThrowsAsync <HttpException>(async() =>
                                                                              await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, () => sqlContext.SaveChangesAsync()));

                    //VERIFY
                    ex.Message.ShouldEqual("NotFound");
                    hasUpdates.ShouldBeTrue();
                    sqlContext.Books.Count().ShouldEqual(0);
                }
        }
        public async Task TestSaveChangesIndirectUpdatesNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    await sqlContext.SaveChangesAsync();
                }
            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    //ATTEMPT
                    var book = sqlContext.Books.Include(x => x.Reviews).Single();
                    book.AddReview(5, "xxx", "yyy");
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.Single(p => p.BookId == book.BookId);
                    noSqlBook.AuthorsOrdered.ShouldEqual("Author1, Author2");
                    noSqlBook.ReviewsCount.ShouldEqual(3);
                }
        }
        public async Task TestGetCosmosClientOnMainDatabasesOk()
        {
            //SETUP
            var mainConfig        = AppSettings.GetConfiguration("../EfCoreSqlAndCosmos/");
            var noSQlDatabaseName = mainConfig["database"];
            var noSqlOptions      = noSQlDatabaseName.GetCosmosDbToEmulatorOptions <NoSqlDbContext>();

            using (var noSqlDbContext = new NoSqlDbContext(noSqlOptions))
            {
                var cosmosClient = noSqlDbContext.Database.GetCosmosClient();
                var database     = cosmosClient.GetDatabase(noSQlDatabaseName);
                var container    = database.GetContainer(nameof(NoSqlDbContext));

                //ATTEMPT
                _output.WriteLine($"SQL count = {noSqlDbContext.Books.Select(_ => 1).AsEnumerable().Count()}");
                using (new TimeThings(_output, "NoSQL count, EF Core"))
                {
                    var result = noSqlDbContext.Books.Select(_ => 1).AsEnumerable().Count();
                }

                using (new TimeThings(_output, "NoSQL count, EF Core"))
                {
                    var result = noSqlDbContext.Books.Select(_ => 1).AsEnumerable().Count();
                }

                using (new TimeThings(_output, "NoSQL count, via client"))
                {
                    var resultSet = container.GetItemQueryIterator <int>(new QueryDefinition("SELECT VALUE Count(c) FROM c"));
                    var result    = (await resultSet.ReadNextAsync()).First();
                }

                using (new TimeThings(_output, "NoSQL count, via client"))
                {
                    var resultSet = container.GetItemQueryIterator <int>(new QueryDefinition("SELECT VALUE Count(c) FROM c"));
                    var result    = (await resultSet.ReadNextAsync()).First();
                }
            }

            var sqlConnection = mainConfig.GetConnectionString("BookSqlConnection");
            var builder       = new DbContextOptionsBuilder <SqlDbContext>()
                                .UseSqlServer(sqlConnection);

            using (var sqlContext = new SqlDbContext(builder.Options))
            {
                _output.WriteLine($"SQL count = {sqlContext.Books.Count()}");
                using (new TimeThings(_output, "SQL count"))
                {
                    var num = await sqlContext.Books.CountAsync();
                }

                using (new TimeThings(_output, "SQL count"))
                {
                    var num = await sqlContext.Books.CountAsync();
                }
            }
        }
        public IActionResult ResetDatabase(
            [FromServices] SqlDbContext context,
            [FromServices] NoSqlDbContext noSqlDbContext,
            [FromServices] IWebHostEnvironment env)
        {
            context.DevelopmentWipeCreated(noSqlDbContext);
            var numBooks = context.SeedDatabase(env.WebRootPath);

            SetupTraceInfo();
            return(View("Message", $"Successfully reset the database and added {numBooks} books."));
        }
        public async Task DeleteNoSqlDatabase()
        {
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);

            using var context = new NoSqlDbContext(builder.Options);
            await context.Database.EnsureDeletedAsync();
        }
        public async Task TestOrderByOk(OrderByOptions orderBy)
        {
            //SETUP
            using (var context = new NoSqlDbContext(_options))
            {
                var service = new ListNoSqlBooksService(context);

                //ATTEMPT
                var books = await(service.SortFilterPageAsync(new NoSqlSortFilterPageOptions
                {
                    OrderByOptions = orderBy
                }));

                //VERIFY
                books.Any().ShouldBeTrue();
            }
        }
        public async Task TestDateFilterFailsDateTimeUtcNow()
        {
            //SETUP
            using (var context = new NoSqlDbContext(_options))
            {
                //ATTEMPT
                var now   = DateTime.UtcNow;
                var books = await context.Books.Where(x => x.PublishedOn < now).ToListAsync();

                var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                              await context.Books.Where(x => x.PublishedOn < DateTime.UtcNow).ToListAsync());

                //VERIFY
                books.Any().ShouldBeTrue();
                ex.Message.ShouldContain("could not be translated.");
            }
        }
        public async Task TestFilterDatesFutureOk()
        {
            //SETUP
            using (var context = new NoSqlDbContext(_options))
            {
                var service = new ListNoSqlBooksService(context);

                //ATTEMPT
                var books = await service.SortFilterPageAsync(new NoSqlSortFilterPageOptions
                {
                    OrderByOptions = OrderByOptions.ByPublicationDate,
                    FilterBy       = BooksFilterBy.ByPublicationYear,
                    FilterValue    = "Coming Soon"
                });

                //VERIFY
                books.All(x => x.PublishedOn > DateTime.UtcNow).ShouldBeTrue();
            }
        }
        public async Task TestCosmosDbCatchFailedRequestOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASE");

            using (var context = new NoSqlDbContext(builder.Options))
            {
                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                var ex = await Assert.ThrowsAsync <HttpException>(async() => await context.SaveChangesAsync());

                //VERIFY
                ex.Message.ShouldEqual("NotFound");
            }
        }
        public TestNoSqlBookRead(ITestOutputHelper output)
        {
            _output = output;
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);

            _options = builder.Options;

            using var context = new NoSqlDbContext(_options);
            context.Database.EnsureCreated();
            if (context.Books.Select(_ => 1).AsEnumerable().Count() < 5)
            {
                var books = NoSqlTestData.CreateDummyBooks(10, true);
                context.AddRange(books);
                context.SaveChanges();
            }
        }
        public async Task TestFilterVotesOk()
        {
            //SETUP
            var year = DddEfTestData.DummyBookStartDate.AddYears(5).Year;

            using (var context = new NoSqlDbContext(_options))
            {
                var service = new ListNoSqlBooksService(context);

                //ATTEMPT
                var books = await service.SortFilterPageAsync(new NoSqlSortFilterPageOptions
                {
                    OrderByOptions = OrderByOptions.ByVotes,
                    FilterBy       = BooksFilterBy.ByVotes,
                    FilterValue    = "2"
                });

                //VERIFY
                books.All(x => x.ReviewsAverageVotes > 2).ShouldBeTrue();
            }
        }
        public async Task TestFilterDatesOk()
        {
            //SETUP
            var year = Math.Min(DateTime.UtcNow.Year, DddEfTestData.DummyBookStartDate.AddYears(5).Year);

            using (var context = new NoSqlDbContext(_options))
            {
                var service = new ListNoSqlBooksService(context);

                //ATTEMPT
                var books = await service.SortFilterPageAsync(new NoSqlSortFilterPageOptions
                {
                    OrderByOptions = OrderByOptions.ByPublicationDate,
                    FilterBy       = BooksFilterBy.ByPublicationYear,
                    FilterValue    = year.ToString()
                });

                //VERIFY
                books.Single().PublishedOn.Year.ShouldEqual(year);
            }
        }
        public async Task TestCosmosDbCatchFailedRequestOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASE");

            using (var context = new NoSqlDbContext(builder.Options))
            {
                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                var ex = await Assert.ThrowsAsync <CosmosException>(async() => await context.SaveChangesAsync());

                //VERIFY
                ex.Message.ShouldStartWith("Response status code does not indicate success: 404 Substatus:");
            }
        }
        public async Task TestCosmosDbLocalDbEmulatorCreateDatabaseOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);

            using (var context = new NoSqlDbContext(builder.Options))
            {
                await context.Database.EnsureCreatedAsync();

                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                await context.SaveChangesAsync();

                //VERIFY
                context.Books.Find(book.BookId).ShouldNotBeNull();
            }
        }
        public async Task TestCosmosDbLocalDbEmulatorCreateDatabaseOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                nameof(TestNoSqlDbContext));

            using (var context = new NoSqlDbContext(builder.Options))
            {
                await context.Database.EnsureCreatedAsync();

                //ATTEMPT
                var book = NoSqlTestData.CreateDummyNoSqlBook();
                context.Add(book);
                await context.SaveChangesAsync();

                //VERIFY
                (await context.Books.CountAsync(p => p.BookId == book.BookId)).ShouldEqual(1);
            }
        }
Example #29
0
        public void TestSaveChangesDirectUpdatesNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    sqlContext.SaveChanges();
                }
            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    //ATTEMPT
                    var book = sqlContext.Books.Single();
                    book.PublishedOn = DddEfTestData.DummyBookStartDate.AddDays(1);
                    sqlContext.SaveChanges();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.Single(p => p.BookId == book.BookId);
                    noSqlBook.PublishedOn.ShouldEqual(DddEfTestData.DummyBookStartDate.AddDays(1));
                    noSqlBook.AuthorsOrdered.ShouldEqual("Author1, Author2");
                    noSqlBook.ReviewsCount.ShouldEqual(2);
                }
        }
        public async Task TestSaveChangesChangeAuthorTwoBooksNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    sqlContext.SeedDatabaseFourBooks();
                }
            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    //ATTEMPT
                    var author  = sqlContext.Authors.Single(x => x.Name == "Martin Fowler");
                    var bookIds = sqlContext.BookAuthors
                                  .Where(x => x.AuthorId == author.AuthorId)
                                  .Select(x => x.BookId).ToList();
                    author.Name = "Different Name";
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(4);
                    var noSqlBooks = noSqlContext.Books.Where(p => bookIds.Contains(p.BookId)).ToList();
                    noSqlBooks.Count.ShouldEqual(2);
                    noSqlBooks.All(x => x.AuthorsOrdered == "Different Name").ShouldBeTrue();
                }
        }