How to use diffrent DbContext per user in mvc core 2.2

by thisisnabi   Last Updated July 12, 2019 14:26 PM - source

i have some company and many user for that. now i need to have one database per company.

have to solve this problem in MVC Core. and control DI



Answers 1


You need to create several DataBaseContext classes like this

 using Microsoft.EntityFrameworkCore;

    namespace Data.Models
    {
        public class FirstDataContext: DbContext
        {
            public DbSet<User> Users{ get; set; }
            public MobileContext(DbContextOptions<MobileContext> options)
                : base(options)
            {

            }
        }


        public class SecondDataContext : DbContext
        {
            public DbSet<User> Users{ get; set; }
            public MobileContext(DbContextOptions<MobileContext> options)
                : base(options)
            {

            }
        }
    }

than on appsettings.json add several connection strings that contains address of database

    {
      "ConnectionStrings": {
        "FirstCompany": "Server=(localdb)\\mssqllocaldb;Database=company1;Trusted_Connection=True;"
      },
         "SecondCompany": "Server=(localdb)\\mssqllocaldb;Database=company2;Trusted_Connection=True;"
      },
    }

than go to StartUp.cs

   public void ConfigureServices(IServiceCollection services)
            {

                string FirstCompany= Configuration.GetConnectionString("FirstCompany");
string SecondCompany= Configuration.GetConnectionString("SecondCompany");

                services.AddDbContext<FirstDataContext>(options =>
                    options.UseSqlServer(connection));

services.AddDbContext<SecondDataContext>(options =>
                    options.UseSqlServer(connection));
                services.AddMvc();
            }

DI:

     public class HomeController: Controller
     {    
          FirstDataContext fdcntxt;
          SecondDataContext sdcntxt;

          public HomeController (FirstDataContext fdcntxt, SecondDataContext sdcntxt)
          {
               this.fdcntxt = fdcntxt;
               this.sdcntxt = sdcntxt;
          }
      }

I think this should be works).

sherox
sherox
July 12, 2019 14:25 PM

Related Questions



Uploading image in MVC .NET core using EF

Updated February 21, 2018 13:26 PM


Read / Print Excel in Asp.net CORE 2 MVC

Updated January 12, 2018 21:26 PM