Skip to content

Instructions 03 EF Core

Christian Nagel edited this page Sep 28, 2023 · 3 revisions

Part 3 - EF Core

You can create a custom data library using EF Core referencing the models package, or just use the NuGet package of the data library: CNinnovation.Codebreaker.Cosmos.

Configure the Cosmos DB context

With the Games API, reference the NuGet package CNinnovation.Codebreaker.Cosmos.

In the games API, program.cs, configure to use the Azure Cosmos DB context to be used inste of the in-memory context depending on the DataStorage configuration.

string dataStorage = builder.Configuration["DataStorage"] ??= "Cosmos";

if (dataStorage == "Cosmos")
{
    builder.Services.AddDbContext<IGamesRepository, GamesCosmosContext>(options =>
    {
        string connectionString = builder.Configuration.GetConnectionString("GamesCosmosConnection") ?? throw new InvalidOperationException("Could not find GamesCosmosConnection");
        options.UseCosmos(connectionString, databaseName: "codebreaker")
            .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    });
}
else if (dataStorage == "SqlServer")
{

}
else
{
    builder.Services.AddSingleton<IGamesRepository, GamesMemoryRepository>();
}

With the appsettings.json file, set a DataStorage key to the Cosmos value.

Cosmos DB Emulator

Startup the Azure Cosmos DB emulator, and create a database named codebreaker, and a container named GamesV3 with the partition key named /PartitionKey.

Create Container

Get the primary connection string from the Cosmos DB emulator, and configure it with ConnectionStrings

{
  "ConnectionStrings": {
    "GamesCosmosConnection": "<use the primary connection string from the Cosmos DB emulator>"
  }
}

Run the service

Run the service and test the API with HTTP files or the Swagger UI. Check for game items to be stored in the database.

Clone this wiki locally