使用多个数据库与单一的DbContext和entites的,并在运行时生成的字符串康涅狄格州 [英] Using multiple Databases with single DbContext and Entites and generating Conn String at runtime

查看:529
本文介绍了使用多个数据库与单一的DbContext和entites的,并在运行时生成的字符串康涅狄格州的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个MVC 5应用程序。起初我是用与EF6数据库的第一种方法单一的数据库,我用我的DbContext实例来访问我的数据库,有102桌。我声明它的实例为:

I am developing an MVC 5 application. Initially I was using single database with EF6 DataBase first approach and I am using my DbContext instance to access my database which have 102 tables. I am declaring its instance as:

私人MyEntities DB =新MyEntities();

private MyEntities db = new MyEntities();

现在我想允许多家公司使用我的应用程序,并为此事我必须为每一个新的公司一个新的数据库。我通过声明另一个构造我的DbContext做到了这一点,如下所示:

Now I want to allow multiple companies to use my application and for that matter I have to create a new database for each new company. I achieved this by declaring another constructor to my DbContext as follows:

public partial class NewEntities : DbContext
{
    public NewEntities(string name)
        : base(name)
    {
    }
}

和则宣称它的实例为:

public NewEntities de = new NewEntities((ConfigurationManager.ConnectionStrings["NewEntities123"]).ToString());

然后我打电话

db.Database.Create();

db.Database.Create();

和我的新的数据库已成功创建。但在这个方案我有我想要添加数据库,每次申报一个新的连接字符串在我的Web.config文件。

and my new database was created successfully. But in this scheme I have to declare a new connection string in my Web.config file each time I want to add a database.

有没有哪里是自动生成的按在配置文件中的公司名称的连接字符串,然后传递给构造函数来创建该名称的新数据库的任何方法?

Is there any method where a connection string is generated automatically as per the company name in config file and then passed to the constructor to create a new database with that name?

此外我还想通过访问与相同的分贝实例和所有的DbContext我的控制器方法,每家公司,让自己的同一code可用于所有公司。我怎么可以访问单一的DbContext及其实例多个数据库?

Moreover I want to access all my controller methods with the same "db" instance and DbContext for every company, so that my same code can be used for all companies. How can I access single DbContext and its instance for multiple databases?

我已经看过<一个href=\"http://stackoverflow.com/questions/7404690/can-you-have-a-dbcontext-that-is-associated-with-multiple-databases\">answer此,因为它是说,没有方法。但如何将我的多用户应用程序的工作?

I have already looked answer to this as it is saying that there is no method. But then How can my application work for multiple Users?

推荐答案

在工作数据库为先,具有映射的EDMX文件,您可以创建和使用数据库这种方式。

When working database-first, having an edmx file with mappings, you can create and use database this way.

添加一个重载的上下文构造(像你一样),例如:

add an overload to your context constructor (as you did), for example:

public TenantDBContainer(string connectionString)
    : base(connectionString)
{
}

然后,当你需要的,如果不存在,用于创建数据库 yourContextInstance.Database.CreateIfNotExists();

var connectionStringTemplate =
    @"metadata=res://*/Models.TenantDB.csdl|res://*/Models.TenantDB.ssdl|res://*/Models.TenantDB.msl;" +
    @"provider=System.Data.SqlClient;" +
    @"provider connection string=""data source=(localdb)\v11.0;" +
    @"initial catalog={0};"+
    @"user id={1};password={2};" +
    @"MultipleActiveResultSets=True;App=EntityFramework"";";

var TenandDBName = "Database Name Based on Tenant";
var TenantUserName = "UserName Based on Tenant";
var TenantPassword = "Password Based on Tenant";
var connectionString = string.Format(connectionStringTemplate, TenandDBName, TenantUserName, TenantPassword);
var db = new TenantDBEntities(connectionString);
db.Database.CreateIfNotExists();

请注意:


  • 这种方式可以为每个租户数据库,并使用它的多租户应用程序。

  • 您不需要改变你的webconfig添加连接字符串在那里,你可以简单地在运行时创建连接字符串。

  • 现在,你可以设计一个结构以获取上下文根据您的租户检测策略

  • This way in a multi-tenant application you can create database per tenant and use it.
  • You don't need to change your webconfig to add connection string there, you can simply create connection string at run-time.
  • Now you can design an structure to get context based on your tenant detection strategy.

作为一个例子,以简化的情况下,假设你有一个地方静态方法返回上下文的实例为你,例如:

As an example to simplify the case, suppose you have a static method somewhere that returns an instance of context for you, for example:

Public class DbHelper
{
    public static TenantDBEntities GetDbContext(string tenantName)
    {
        var connectionStringTemplate =
            @"metadata=res://*/Models.TenantDB.csdl|res://*/Models.TenantDB.ssdl|res://*/Models.TenantDB.msl;" +
            @"provider=System.Data.SqlClient;" +
            @"provider connection string=""data source=(localdb)\v11.0;" +
            @"initial catalog={0};"+
            @"integrated security=True;" +
            @"MultipleActiveResultSets=True;App=EntityFramework"";";

        var TenandDBName = "TenantDB_" + tenantName;
        var connectionString = string.Format(connectionStringTemplate, TenandDBName);
        var db = new TenantDBEntities(connectionString);
        db.Database.CreateIfNotExists();

        return db;
    }
}

和想我的房客dettection策略是简单地根据请求的URL或别的东西。

And suppose my tenant dettection strategy is simply based on request url or something else.

现在例如在ProductController的索引中的动作就可以使用这种方式;

Now for example in ProductController in Index action you can use it this way;

public ActionResult Index()
{
    var tenantName = "Get tenant based on your strategy, for example tenant1 or tenant2";
    var db= DbHelper.GetDbContext(tenantName)
    var model= db.Products.ToList();
    return View(model);
}

在每个租户正在与这个动作,它连接到适用于租户数据库,如果数据库不存在,首先创建然后使用它。

When each tenant is working with this action, it connects to database suitable for that tenant, and if the database not exists, first creates it then uses it.

这样每个租户将会看到自己的产品。

This way each tenant will see his own products.

这篇关于使用多个数据库与单一的DbContext和entites的,并在运行时生成的字符串康涅狄格州的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆