.Net Core 中具有独立数据库的多租户系统

Multi-Tenancy System With Separate Databases in .Net Core

我正在尝试为每个租户策略创建实施数据库。但我不明白我实际上将如何做 that.I 遵循此 link https://www.codeproject.com/Articles/848111/Multi-Tenancy-System-With-Separate-Databases-in-MV 但我使用 asp.net 核心 MVC。我是绝对的 beginner.how 我为不同的用户创建了一个单独的数据库。请帮忙

不确定您的模型设计如何,但您想要的是如何在项目中创建和使用多个数据库。

您可以按照以下步骤操作:

  • 创建第一个数据库

    1. 模型设计:

      public class Account
      {
          public int Id { get; set; }
          public string Name { get; set; }
      }
      
    2. 创建 DbContext:

      public class FirstContext : DbContext
      {
           public FirstContext (DbContextOptions<FirstContext> options)
               : base(options)
           {
           }
      
           public DbSet<Account> Account { get; set; }
      }
      
    3. 在appsettings.json中添加连接字符串:

      "ConnectionStrings": {
          "FirstContext": "Server=(localdb)\mssqllocaldb;Database=FirstUser;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
      
    4. 配置Startup.cs:

       public class Startup
       {
           public Startup(IConfiguration configuration)
           {
               Configuration = configuration;
           }
      
           public IConfiguration Configuration { get; }
      
           public void ConfigureServices(IServiceCollection services)
           {
               services.Configure<CookiePolicyOptions>(options =>
               {
                   // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                   options.CheckConsentNeeded = context => true;
                   options.MinimumSameSitePolicy = SameSiteMode.None;
               });
               services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      
                //add this...
               services.AddDbContext<FirstContext>(options =>
                   options.UseSqlServer(Configuration.GetConnectionString("FirstContext")));
           }
      
           public void Configure(IApplicationBuilder app, IHostingEnvironment env)
           {
      
               app.UseHttpsRedirection();
               app.UseStaticFiles();
               app.UseCookiePolicy();
      
               app.UseMvc(routes =>
               {
                   routes.MapRoute(
                       name: "default",
                       template: "{controller=Home}/{action=Index}/{id?}");
               });
           }
       }
      

    5.Run 创建数据库的命令(这种方式在 EF Core 中称为代码优先):

    PM> add-migration init
    PM> update-database
    

    6.Then 您可以在 (localdb)\MSSQLLocalDB->Database 中找到数据库 SQL Server Object Explorer(在菜单选项卡中打开 View-> 选择 SQL Server Object Explorer):

  • 创建第二个数据库

    重复 1-4 步:

    型号:

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    数据库上下文:

     public class SecondContext : DbContext
     {
         public SecondContext(DbContextOptions<FirstContext> options)
             : base(options)
         {
         }
    
         public DbSet<User> User { get; set; }
     }
    

    appsettings.json:

    "ConnectionStrings": {
     "FirstContext": "Server=(localdb)\mssqllocaldb;Database=FirstContext-ed05c500-1e05-4d2c-876d-02172e464153;Trusted_Connection=True;MultipleActiveResultSets=true",
     "SecondContext": "Server=(localdb)\mssqllocaldb;Database=SecondUser;Trusted_Connection=True;MultipleActiveResultSets=true"
     }
    

    Startup.cs:

    services.AddDbContext<FirstContext>(options =>
                         options.UseSqlServer(Configuration.GetConnectionString("FirstContext")));
    
     //add this...
    services.AddDbContext<SecondContext>(options =>
                         options.UseSqlServer(Configuration.GetConnectionString("SecondContext")));
    

    不同的是你包含多个dbcontext,所以你在运行命令创建数据库时需要指定dbcontext名称:

    PM> add-migration init2 -context secondcontext
    PM> update-database -context secondcontext
    
  • 如何获取不同的用户数据:

    public class AccountsController : Controller
    {
         private readonly FirstContext _context;
         private readonly SecondContext _context2;
         public AccountsController(FirstContext context, SecondContext context2)
         {
             _context = context;
             _context2 = context2;
         }
    
         public async Task<IActionResult> Index()
         {
             var user1 = _context.Account.ToList();
             var user2 = _context2.User.ToList();
             return View();
         }
    }