Entity Framework Core And Cosmos DB With Blazor

In my first article, I have described Azure Cosmos DB Table API, and as I have promised you in this article, I will explain the Azure Cosmos DB SQL API, but I would do it differently. To make the article more comprehensive, I have included two other topics, Entity Framework Core and Blazor. Entity Framework Core uses Azure Cosmos DB SQL API. So, I have shortly introduced the Azure Cosmos DB SQL API, and I have created a demo application. The Demo application is used CosmosDb Emulator as a backend and Entity Framework Core as ORM with Cosmos DB Provider, and the rest is done with Blazor.
 
Source Code
 
 
You can read the first part from here - 
The need for the relational database,
Image -1- There was a need for relational database
 
The most persistence problems between 1990 until 2003 are solved with RDBM.
Image -1- RDBM solve all problems
 
The NoSQL revolution has begun because of:
  
Image -3- NoSQL revolution
 

Azure Cosmos DB SQL API

 
Azure Cosmos DB SQL API belongs to Document store databases (NoSQL). It uses JSON to store the documents, and it allows you to query the database with a similar syntax to SQL.
 

What is Document store database?

 
Stores the entities as documents (JSON, BSON, XML, etc.). They are different from the relational databases, but you can compare the taxonomy, like below.
 
 Document store databases  RDBMS
 Collection  Table
 Row  Document                  
 Column  Field            
 

Important terms related to Document Store Databases

 
Schema Free
You can fill in a document with whatever data you want. Documents might have different structures.
 
Denormalized
You do not have to be afraid of data duplication.
 
Strong Consistency / Eventual Consistency
 
Performance
You can index the fields for faster performance.
 
Easy to Scale-out
Because the data is combined in Aggregate, it is easy to scale the database out. In our example, we can handle one user with a sub-collection of posts as one. Aggregate is similar to Transactions-Concept in RDBM. For more information about the Aggregate and domain entities, please refer to Eric J. Evans' book - Domain-Driven Design.
 
Alternatively, you can watch Martin Fowler's video on this YouTube Link.
 
Example
 
In my demo, I have created a very simple community demo application. The domain model consists of two classes, User and Post, as shown below,
Domain Entities
Image -4- Domain Entities
 
User contains a sub-collection for Posts. You can achieve this relationship with the document store database in one collection, for example, Users Collection includes the JSON documents for the Users Entities, and the Posts are embedded as shown below,
 
Image -4- Users Collection/Container
 

Entity Framework Core

 
Entity Framework is designed originally for the relational database system, which helps you to solve different RDBM problems like schema changes. However, with time we have seen that ORM Tools can do more than the relational database. ORM Tools offer an abstract layer between the databases and your business logic. So, they help you to change your backend without many efforts. That's why it makes sense even to use it with non-relation databases. I have before a long time tried to use EF with NoSQL but at that time. Unfortunately, the technology was not ripe enough so that I can use it in the production code.
 
Now with Entity Framework Core everything is changed. One important design decision in EF Core is to use it with NoSQL databases. This is not an easy job because of the nature of the NoSQL databases are very different. They are not based on a standard theory or of a standard query language. Fortunately, we have LINQ and Lambda Expressions. Those technologies became famous and well accepted among the developers so that they can help the EF Core team to offer a unique abstraction layer for all those NoSQL database models.
 

Blazor

 
Allows you to build interactive web UIs using C# instead of JavaScript. Because I am a C# Developer, I love to use it.
Enough theory and let us switch to our Community example.
 

Requirements for the Demo Application

 
Visual Studio 2019 Preview
https://docs.microsoft.com/de-de/visualstudio/releases/2019/release-notes-preview
 
.NET Core 
.Net Core Version 3.0 Preview 6
.Net Core Version 2.2
https://dotnet.microsoft.com/download/dotnet-core/3.0
 
Azure Cosmos Emulator
https://docs.microsoft.com/de-de/azure/cosmos-db/local-emulator
 
First, I have created the domain entities
  1. public class User  
  2. {  
  3.     public Guid UserId { getset; }  
  4.   
  5.     public string Name { getset; }  
  6.   
  7.     public ICollection<Post> Posts { getset; }  
  8. }  
  9.   
  10. public class Post  
  11. {  
  12.     [Key]  
  13.     public Guid PostId { getset; }  
  14.   
  15.     public string Title { getset; }  
  16.   
  17.     public string Content { getset; }  
  18.   
  19.     public User User { getset; }  
  20. }  
I have added the database context "CommunityDbContext".
  1. public class CommunityDbContext : DbContext  
  2. {  
  3.     public DbSet<User> Users { getset; }  
  4.   
  5.     public DbSet<Post> Posts { getset; }  
  6.   
  7.     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  8.     {  
  9.   
  10.       var Endpoint = "https://localhost:8081";  
  11.       var Key = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";  
  12.   
  13.       optionsBuilder.UseCosmos(  
  14.                                Endpoint,  
  15.                                Key,  
  16.                                 "CommunityDatabase")  
  17.                                .UseLoggerFactory(GenerateLoggerFactory())  
  18.                                .EnableSensitiveDataLogging(true);  
  19.     }  
  20.   
  21.     protected override void OnModelCreating(ModelBuilder modelBuilder)  
  22.     {  
  23.       modelBuilder.Entity<User>().ToContainer("Users");  
  24.       modelBuilder.Entity<User>().OwnsMany(s => s.Posts);  
  25.       base.OnModelCreating(modelBuilder);  
  26.     }  
  27.   
  28.     private ILoggerFactory GenerateLoggerFactory()  
  29.     {  
  30.       var serviceCollection = new ServiceCollection();  
  31.       serviceCollection.AddLogging(builder => builder.AddConsole().AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Trace));  
  32.   
  33.       return serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>();  
  34.     }  
  35. }  
Note
I have installed the Cosmos Db from NuGet,
 
Install-Package Microsoft.EntityFrameworkCore.Cosmos -Version 2.2.0-preview3-35497
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.6
Install-Package Microsoft.Extensions.Logging.Console -Version 2.2.0
 
I have used .NET Core Version 2.2 because the .NET Core 3.0 not work correctly with the Cosmos Provider does.
 
Note
Blazor Use .NET Core 3.x Preview! 
 
I have copied the Endpoint and the Key from the CosmosDb Emulator as shown below,
 
Image -5- CosmosDb Emulator
 
I have enabled the query debugging as following:
  1. serviceCollection.AddLogging(builder => builder.AddConsole().AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Trace));  
DbLoggerCategory.Database.Command dumps the database query. You can change it to Transaction or Connection depending on your needs.
 
 
Image -6- Query and Command Logs
 
The below line code is critical,
  1. modelBuilder.Entity<User>().OwnsMany(s => s.Posts);  
If you remove this line and execute the application, then the Post will not be embedded inside the User Collection (Container).
 
More Information (mongoDB).
 
Model One-to-Many Relationships with Embedded Documents
https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/
 
Model One-to-Many Relationships with Document References
https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/
 
To make it more interesting, I have added a Repository class which is responsible for the CRUD operations.
  1. public class UserRepository : IDisposable  
  2. {  
  3.     private readonly CommunityDbContext communityDbContext;  
  4.   
  5.     public UserRepository(CommunityDbContext communityDbContext)  
  6.     {  
  7.       this.communityDbContext = communityDbContext;  
  8.     }  
  9.   
  10.     public void Add(User user)  
  11.     {  
  12.       communityDbContext.Users.Add(user);  
  13.     }  
  14.   
  15.     public void Delete(User user)  
  16.     {  
  17.       communityDbContext.Users.Remove(user);  
  18.     }  
  19.   
  20.     public IQueryable<User> Find(Expression<Func<User, bool>> expression)  
  21.     {  
  22.       return communityDbContext.Users.Where(expression);  
  23.     }  
  24.   
  25.     public ICollection<User> GetAll()  
  26.     {  
  27.       return communityDbContext.Users.ToList();  
  28.     }  
  29.   
  30.     public void Commit()  
  31.     {  
  32.       communityDbContext.SaveChanges();  
  33.     }  
  34.   
  35.     public void Include(string navigationPropertyPath)  
  36.     {  
  37.       _ = communityDbContext.Users.Include(navigationPropertyPath);  
  38.     }  
  39.   
  40.     public void GenerateDatabase()  
  41.     {  
  42.       this.communityDbContext.Database.EnsureDeleted();  
  43.       this.communityDbContext.Database.EnsureCreated();  
  44.     }  
  45.   
  46. …  
The below two lines are to delete and generate the database on the fly.
  1. this.communityDbContext.Database.EnsureDeleted();  
  2. this.communityDbContext.Database.EnsureCreated();  
  1. _ = communityDbContext.Users.Include(navigationPropertyPath);  
This line to Include the Posts to the Users (Eager Loading). I do not like Lazy Loading, so please try to avoid it in your design too.
Let us take the second step. We need a UI for our application. Blazor is suitable for you as a C# Developer so, I have used it.
 
You do not have to install Blazor as in the past!
 
https://marketplace.visualstudio.com/items?itemName=aspnet.blazor 
 
NOTE
This Blazor Visual Studio extension is obsolete and no longer required to use Blazor.
 
To get the latest Blazor templates install them from the command-line. Visual Studio (16.3 or later) will detect that the templates have been installed and surface them to you without the need for any additional extensions. If you already have this extension installed, you can go ahead and uninstall it.”
 

What I did - step by step

 
 
 
 
 
 
Your project should like,
 
 
 
I have to edit the WeatherTemplate and change to UserService as follows,
  1. using CosmosDbSQLAPI;  
  2. using Entities;  
  3. using System.Collections.Generic;  
  4. using System.Collections.ObjectModel;  
  5. using System.Linq;  
  6.   
  7. namespace CommunityWebApp.Data  
  8. {  
  9.   public class UserService  
  10.   {  
  11.     public UserService()  
  12.     {  
  13.       // Generate some dummy data.  
  14.       using (var userRepository = new UserRepository(new CommunityDbContext()))  
  15.       {  
  16.         userRepository.GenerateDatabase();  
  17.   
  18.         for (var i = 0; i < 5; i++)  
  19.         {  
  20.           userRepository  
  21.             .Add(  
  22.                  new User  
  23.                  {  
  24.                    Name = "Bassam_" + i,  
  25.                    Posts = new Collection<Post> {  
  26.                                                   new Post {  
  27.                                                               Title = "www.bassam.ml",  
  28.                                                               Content ="My page"  
  29.                                                             }  
  30.                                                  }  
  31.                  }  
  32.                 );  
  33.         }  
  34.   
  35.         userRepository.Commit();  
  36.       }  
  37.     }  
  38.   
  39.     public void AddPost(string username)  
  40.     {  
  41.       // Todo async and  Error code!  
  42.       using (var userRepository = new UserRepository(new CommunityDbContext()))  
  43.       {  
  44.         var user = userRepository.Find(u => u.Name == username).Single();  
  45.         user.Posts.Add(new Post() { Content = "CSharp", Title = "I love you CosmosDb!" });  
  46.         userRepository.Commit();  
  47.       }  
  48.     }  
  49.   
  50.     public void DeleteUser(string username)  
  51.     {  
  52.       // Todo async and  Error code!  
  53.       using (var userRepository = new UserRepository(new CommunityDbContext()))  
  54.       {  
  55.         var user = userRepository.Find(u => u.Name == username).Single();  
  56.         userRepository.Delete(user);  
  57.         userRepository.Commit();  
  58.       }  
  59.     }  
  60.   
  61.     public ICollection<User> GetUsers()  
  62.     {  
  63.       // Todo async and Error code!  
  64.       using (var userRepository = new UserRepository(new CommunityDbContext()))  
  65.       {  
  66.         userRepository.Include(nameof(User.Posts));  
  67.         return userRepository.GetAll();  
  68.       }  
  69.     }  
  70.   }  
  71. }  
The code above creates five users by initialization and adding for each user a dummy post.
 
The other methods are used to demonstrate CRUD operations.
 
I did everything synchronous just for demo in production code you have to make everything asynchronous.
 
Also, I have called the service on the Blazor page as follows,
  1. @page "/fetchdata"  
  2. @using CommunityWebApp.Data  
  3. @using  Entities  
  4. @inject UserService UserService  
  5.   
  6. <h1>Community members</h1>  
  7.   
  8. <p>This component demonstrates fetching data from Entity Framework Core and Cosmos DB.</p>  
  9.   
  10. @if (users == null)  
  11. {  
  12.     <p><em>Loading... From Cosmos Emulator!</em></p>  
  13. }  
  14. else  
  15. {  
  16.     <label style="color: red;">@ErrorText</label>  
  17.     <br />  
  18.     <input @bind-value="@Username" @bind-value:event="oninput" placeholder="Enter User Name" />  
  19.     <button class="btn btn-primary" @onclick="@AddPost">Add Post</button>  
  20.     <button class="btn btn-primary" @onclick=@DeleteUser>Delete User</button>  
  21.   
  22.     <table class="table">  
  23.         <thead>  
  24.             <tr>  
  25.                 <th>Name</th>  
  26.                 <th>Id</th>  
  27.                 <th>Post Count</th>  
  28.   
  29.             </tr>  
  30.         </thead>  
  31.         <tbody>  
  32.             @foreach (var user in users)  
  33.             {  
  34.                 <tr>  
  35.                     <td>@user.Name</td>  
  36.                     <td>@user.UserId</td>  
  37.                     <td>@user.Posts.Count()</td>  
  38.   
  39.                 </tr>  
  40.             }  
  41.         </tbody>  
  42.     </table>  
  43. }  
  44.   
  45. @code {  
  46.     string Username { getset; } = string.Empty;  
  47.     string ErrorText { getset; } = string.Empty;  
  48.   
  49.     ICollection<User> users;  
  50.   
  51.     void AddPost()  
  52.     {  
  53.         ErrorText = string.Empty;  
  54.         var user = users.SingleOrDefault(x => x.Name == Username);  
  55.         if (user == null)  
  56.         {  
  57.             // error user, not exits!   
  58.             ErrorText = "User does not exist!";  
  59.             return;  
  60.         }  
  61.   
  62.         UserService.AddPost(Username);  
  63.   
  64.         // Reload users.  
  65.         users = UserService.GetUsers();  
  66.     }  
  67.   
  68.     void DeleteUser()  
  69.     {  
  70.         ErrorText = string.Empty;  
  71.         var user = users.SingleOrDefault(x => x.Name == Username);  
  72.         if (user == null)  
  73.         {  
  74.             // error user, not exits!   
  75.             ErrorText = "User does not exist!";  
  76.             return;  
  77.         }  
  78.   
  79.         UserService.DeleteUser(Username);  
  80.   
  81.         // Reload users.  
  82.         users.Remove(user);  
  83.     }  
  84.   
  85.     protected override async Task OnInitAsync()  
  86.     {  
  87.         await Task.Run(() => users = UserService.GetUsers());  
  88.     }  
  89. }  
When you press F5, then you should see the data in the browser.
 
 
You can add more post to the user or delete a user. However, before we are doing that, let us check the database and the Logs.
 
 
Also, here you can see the Users Collection (Container is the new name). That's because I have defined that in the DbContext as follows,
  1. modelBuilder.Entity<User>().ToContainer("Users");
If this line does not exist, then everything stored in the CommunityDbContext as shown in the image -4- above. To get rid of the DbCummnityDbContext container, you have to change the default container name.
 
I have clicked a few times on the Add Post button, as shown below.
 
 
As you can see below, the Posts are added to the selected user. Let us see the database.
 
 
Finally, I have deleted the user with the name "Bassam_0".
 
 
So as we can see, the user is deleted 😊.
 

Summary

 
Azure Cosmos DB SQL API is a document-based database and it can be easily used with Entity Framework Core.
 
Entity Framework Core supports NoSQL databases and gives you a beautiful abstraction to your NoSQL storage models. The code sample for this article is mixing between three Microsoft technologies (Cosmos Db SQL API and Entity Framework, Blazor). I love all those technologies, and Blazor is my superhero so that I do not have to learn JavaScript.


Similar Articles