Generic Repository in C#
Learn how to use the Cosmos DB C# SDK to perform read and write operations in a repository.
Introduction
In this lesson, we’ll learn how to use Container to perform the classic CRUD operations on a document:
Create
Read
Update
Delete
Generic repository
Most operations on documents are independent of the container. For this reason, we’ll implement a generic repository.
Let’s start creating two files in a Repositories folder in the GameStore.Repositories namespace:
IRepository.csRepository.cs
public interface IRepository<TItem> { }public class Repository<TDoc>: IRepository<TItem> { }
Constructor
The most important object when working with documents in the SDK is Container, so we need one in Repository.
As always, there are different ways to achieve this. We prefer the following:
private readonly Container _container;public Repository(CosmosClient cosmosClient, string databaseName, string containerName){_container = cosmosClient.GetContainer(databaseName, containerName);}
Here, we provide from the outside, all three parameters needed by GetContainer.
Creating, updating, and deleting a document
Let’s start with the three write operations. Implementation is no more than proxy calls to the Cosmos SDK.
The short form of update or ...