Skip to content

Version320 Create Cosmos DB options

Jon P Smith edited this page Jan 4, 2021 · 2 revisions

Version 3.2.0 - Extension for setting up Cosmos DB options linked to Azure Cosmos DB Emulator

If you are testing Cosmos DB, then the Azure Cosmos DB Emulator is a great tool to use. It runs locally on the development system and allows you to test Cosmos DB queries without paying for a Cosmos DB database on Azure.

I have added two versions of the extension methods. Both of then creates Cosmos DB options where the Database/Container is held in the Azure Cosmos DB Emulator, but offer different options to define the database name

They are:

this.GetCosmosDbToEmulatorOptions<T>()

This uses the given object's name as the database name. Here is an example:

public async Task TestAddCosmosBookWithReviewsOk()
{
    //SETUP
    var options = this.GetCosmosDbToEmulatorOptions<CosmosDbContext>();
    using var context = new CosmosDbContext(options);
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();

    //ATTEMPT
    var cBook = new CosmosBook
    {
        CosmosBookId = 1,
        Title = "Book Title",
        PublishedDate = new DateTime(2019, 1,1),
    };
    context.Add(cBook);
    await context.SaveChangesAsync();

    //VERIFY
    await context.Books.FindAsync(1).ShouldNotBeNull();
}

You do have the option to make a database name unique to the method that calls it by setting the makeMethodUnique parameter to true. e.g.

public async Task TestWithDatabaseNameUniqueOk()
{
    //SETUP
    var options = this.GetCosmosDbToEmulatorOptions<CosmosDbContext>(true);
    using var context = new CosmosDbContext(options);

    //... etc.
}

"DatabaseName".GetCosmosDbToEmulatorOptions<T>()

This uses the given string as the database name. e.g.

public async Task TestWithGivenNameOk()
{
    //SETUP
    var options = "MyDatabasName".GetCosmosDbToEmulatorOptions<CosmosDbContext>(true);
    using var context = new CosmosDbContext(options);

    //... etc.
}
Clone this wiki locally