top of page

Configure Multiple DBs with Repository pattern in .Net Core



To configure mongoDB, we need to install mongoDB driver for C#, this we can install via NuGet package manager. After installation we need connection string and database name which we usually define in our appsettings.json file as shown below:


"Connection": {
    "FirstDbConnectionString": "{Your_First_DB_Connection_String}",
    "FirstDbName": "{Your_First_DB_Name}",
    "SecondDbConnectionString":"{Your_Second_DB_Connection_String}",
    "SecondDbName": "{Your_Second_DB_Name}",
},

Connection string


We have connection string and DB name for two databases. Now let’s configure them in ConfigureServices method in startup.cs file


Public Class MultipleDbContext {
    public IMangoDatabase FirstDb { get; set;}
    public IMangoDatabase SecondDb {get; set;}
}

MultipleDbContext.cs



//Configuration for mangoDB Context
services.Configure<MultipleDbContext>( config => {
    config.FirstDb = new 
    MangoClient(Configuration["Connection:FirstDbConnectionString"])
    .GetDatabase(Configuration["Connection.FirstDbName"]);
    
    config.SecondDb =  new 
    MangoClient(Configuration["Connection:SecondDbConnectionString"])
    .GetDatabase(Configuration["Connection:SecondDbName"]);
});

Startup.cs


Now we need our repository through which our business layer will communicate to perform CRUD operations in DB. Let’s create repository and add following configuration:


public abstract class GenericRepository<TEntity> : IGenericRepository<TENtity> where TEntity : BaseEntity 
{
    Protected readonly IMangoDatabase FirstDbContext;
    Protected readonly IMangoDatabase SecondDbContext;
    
    public IMangoCollection<TEntity> FirstDbCollection { get; }
    
    public IMangoCollection<TEntity> SecondDbCollection { get; }
    
     protected GenericRepository(IOptions<MultipleDbContext> options){
         try {
             FirstDbContext = options.Value,FirstDb; 
             SecondDbContext = options.Value.SecondDb;
             
             FirstDbCollection = FirstDbContext.GetCollection<TENtity>
             (typeof(TEntity).Name);
             
             SecondDbCollection = SecondDbContext.GetCollection<TEntity> 
             (typeof(TEntity).Name);
         } Catch (Exception) {
             throw;
         }
     }

Repository.cs


We are almost done. So far we have configured multiple DBs and also configured our repository to communicate with those DBs. Only thing is left to perform CRUD operations via repository.


public async Task<TEntity> FirstDbGet(string id) 
{
    try {
        TEntity entity = await this.FirstDbCollection.Find
                    (x => x.ID == id).SingleOrDefaultAsync();
        
        return entity;
    } catch(Exception) {
        throw;
    }
}

Get data from first DB


public async Task<TEntity> SecondDbGet(String id) {
    try {
        TEntity entity = await this.SecondDbCollection.Find (x => x.ID == id).SingleOrDefaultAsync();
        
        return entity;
    } catch (Exception) {
        throw;
    }
}

Get data from second DB


In our above two snippets, we can see how easy it is to get data from both First DB and Second DB. Only change we did is collection name which has been attached to their individual DB context. We can perform other CRUD operations in similar fashion.



Source: Medium - Vipin Sharma


The Tech Platform

0 comments

コメント


bottom of page