Connecting to database for Multi-Tenant application?

前端 未结 1 794
Happy的楠姐
Happy的楠姐 2020-12-12 04:29

I am in the process of creating a Multi-Tenant asp.net application.

I am deciding between separate MSSQL databases or schemas.

However, I cannot find any inf

1条回答
  •  感情败类
    2020-12-12 04:47

    If you have set up multiple database for multiple tenants, you can create connection string based on the tenant.

    You can simply add an overload to your db context constructor that accepts connection string as input:

    public partial class SampleDbEntities
    {
        public SampleDbEntities(string connectionString)
            : base(connectionString)
        {
        }
    }
    

    Then wherever you need to create an instance of your db context, use this overload and inject suitable username and password in the connection string based on your tenant detection strategy.

    For example when your connection string looks like this:

    var connectionTemplate =
        @"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;" +
        @"provider=System.Data.SqlClient;" +
        @"provider connection string=""data source={0};" +
        @"initial catalog={1};" +
        @"persist security info=True;" +
        @"user id={2};" +
        @"password={3};" +  
        @"MultipleActiveResultSets=True;App=EntityFramework""";
    
    string connection = string.Format(connectionTemplate, 
        @"(localdb)\v11.0", @"TestDB", @"user1" , @"password1");
    
    var db = new SampleDbEntities(connection);
    

    Note:

    • Create connection string template based on the connection string which is in your web.config.

    0 讨论(0)
提交回复
热议问题