Azure, Cosmos DB, EF Core, Entity Framework Core, Microsoft

Azure Cosmos DB with EF Core

It feels great to see you guys back. It will be fantastic if you Like and Share your feedback in the comment section.


Download complete code here


Earlier blog, we discussed about how to connect to and manage data on Microsoft Azure Cosmos DB using direct CosmosDB APIs. This time I am taking same to next level with integrating Microsoft Azure Cosmos DB with Entity Framework Core. This is very simple and believe me it just took couple of hours for me to upgrade earlier application code to make it working. So why to make you all wait, lets get our hands onto Visual Studio Code and learn these points:

  • Required Packages
  • Creating Model(s)
  • Creating DbContext
  • Connecting and Managing Data
Application Output/Result

Tips & Tricks: For my local playground, I am using Azure Cosmos DB Emulator. You can surely use your Azure subscription for the same.

Azure Cosmos DB Emulator
  • Once the Emulator started successfully, it will open the instance in default browser at default Port# 8081 on your localhost.
  • You can click on “Quick Start” section on the left to navigate to the page which has connection/client details.
  • EF Core DbContext will need two property values from Quick Start page:
    • Endpoint is address to host/server
    • Primary Key is unique hash/authentication key for client to connect successfully.

Required Packages

<ItemGroup>
  <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.4" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Cosmos" Version="2.2.4" />
</ItemGroup>

Mainly it needs above listed two packages. You can copy and add above code to your Visual Studio Code Project file. Or you can use dotnet add package <package_name> syntax to add them manually using console.


Creating Model(s)

Azure Cosmos DB Sample Data based on EF Core Model
using System;

namespace iValera.CosmosDB.EFCore
{
    public class Employee
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
}

By looking at above sample model, it looks pure POCO object, that is how it is expected for Azure Cosmos DB. Applying too many Component Model and EF DataAnnotations may create issues while mapping models and creating relationships.

Since “id” and few more system defined properties are by default added by Azure Cosmos DB, we can avoid adding them or keep them ReadOnly. Most of the time, we need “id” property to uniquely identify object instance and request for Add/Modify action on DbContext.

Tips & Tricks: In Azure Cosmos DB, each Model stored as unique document with id. So be careful while defining Foreign Keys & References through EF Core.


Creating DbContext

Post Creation of EF Core DbContext
using System;
using Microsoft.EntityFrameworkCore;

namespace iValera.CosmosDB.EFCore
{
    public class DataContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseCosmos(
                serviceEndPoint: "https://localhost:8081",
                authKeyOrResourceToken: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
                databaseName: "iValera.CosmosDB"
            );
        }
    }
}
Azure Cosmos DB Post Setting optionsBuilder

Being Console App, we are going to override OnConfiguring method of EF Core DbContext class and populate optionsBuilder parameter with Azure Cosmos DB connection details; mainly End Point, AuthKey and Name of Database. Instead of hard-coding, I advise to configure these values in some file and take it from there.

Tips & Tricks: Name of your Azure Cosmos DB Collection will be name of instance of DbContext class. In case we have multiple instances of DbContext classes, this will create multiple Azure Cosmos DB Collection.


Connecting and Managing Data

using System;

namespace iValera.CosmosDB.EFCore
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new DataContext())
            {
                context.Database.EnsureCreated();
            }

            AddObject();
        }

        private static void AddObject()
        {
            var employee = new Employee()
                {
                    Id = Guid.NewGuid(),
                    Name = "Sample Object"
                };

            using (var context = new DataContext())
            {
                context.Employees.Add(employee);
                context.SaveChanges();
            }
        }
    }
}

Above code is self explanatory but I would like to emphasise on Row# 11. On Row# 11, we are requesting EF Core to make sure respective database & collection exists; if not, create one. It is highly possible in your scenario this is not applicable or not required so just be aware of it.

Tips & Tricks: Other than configuration of DbContext, most of the other things related to EF Core remains same. This is very big plus point where we have lot more Models and complexity of application.


Yes, one more chapter is done with this. So be happy learning, sharing and helping community. Do read previous blogs and I will come back with with more to read soon.

Advertisements

2 thoughts on “Azure Cosmos DB with EF Core

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s