This post is about working with Cosmos DB SQL Provider for Entity Framework Core. Azure Cosmos DB is Microsoft’s globally distributed, multi-model database. With the click of a button, Azure Cosmos DB enables you to elastically and independently scale throughput and storage across any number of Azure’s geographic regions.
First you need to install the EF Core provider for Cosmos DB. You can get it from NuGet.
Once you install it via dotnet add package Microsoft.EntityFrameworkCore.Cosmos.Sql --version 2.2.0-preview1-35029. Once you install it, you can modify the Startup class code.
For this post I am using Cosmos DB emulator. I am reading it from appsettings.json file. Here is the Endpoint URI and Private Key.
Here is my model class, the Id property type is string, provider will generate the Id automatically.
And here is the DbContext class, in this class OnModelCreating method is important, without this Cosmos DB driver can’t get the collection name from entity class.
Now you can use the DbContext object in controller class and execute the CRUD operations. Also you need to create the Database and Collection in the emulator, otherwise it won’t work properly. Here is the POST implementation.
Here is the Postman request
And here is the data in Cosmos DB Emulator.
The Cosmos DB SQL provider is in preview, so the API may change in future. You can find the source code of this post in here. If you face any issues in the implementation, let me know.
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.
Did you like this article? Share it with your friends