MVC4多个数据库 [英] MVC4 Multiple Databases

查看:159
本文介绍了MVC4多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC4框架和技术的新手.一直在使用许可应用程序,该应用程序必须对不同的产品使用不同的数据库(每个数据库包含一个产品的少数几个表-全部由专有许可工具生成).我的应用程序应该能够在各种产品上支持CRUD功能,因此每种产品都需要多个与不同模型相关的DbContext对象.

I'm new to MVC4 framework & been working on an Licensing application that must use different databases for different products (each database contains handful tables for one product - all generated by proprietary licensing tool). My application shall be able to support CRUD functions on various products, thus requiring more than one DbContext objects in relation to different model for each product.

据我所知,每个这样的DbContext对象在Web.config文件中都需要一个连接字符串.我正在努力使用DropDownList控件列出(Index.cshtml)各种产品的现有许可证,因为每当用户从DropDownList控件中选择其他产品时,每种产品我都需要连接到不同的数据库

As far as I know, each such DbContext object requires a connection string in the Web.config file. I'm struggling to list (Index.cshtml) existing licences for various products, using DropDownList control, as for each product I'd need to connect to a different database whenever the user choose a different product from the DropDownList control.

任何帮助将不胜感激.谢谢.

Any help will be highly appreciated. Thanks.

推荐答案

据我所知,核心问题是,每当用户从DropDownList选择不同的产品时,您都在努力连接到不同的数据库.如您所说,是的DbContext对象需要Web.config文件中的连接字符串.您可以在配置中指定多个连接字符串.
另外,您绝对可以将不同的连接字符串传递给 DBContext构造函数.通常,您的DAL/数据访问层或存储库层将从Web.Config/App.config中提取适当的连接字符串,并将其传递给DBContext构造函数.在此处

As I understand your question, the core issue is you are struggling to connect to a different db, whenever user selects a different product from a DropDownList. As you said, yes DbContext object requires a connection string in the Web.config file. You can specify multiple connection strings in a config.
Also you can definitely pass different connection strings to DBContext constructor. Typically your DAL/Data Access Layer or Repository layer would pull appropriate connection string from the Web.Config/App.config and pass it to the DBContext constructor. See a similar approach here and here.

更新:

您不能与多个数据库共享同一DbContext.您需要为每个数据库多个DbContext .

You cannot share the same DbContext with multiple databases. You need multiple DbContexts for each of your DB.

其他 很少这样做,但是如果您使用重新存储"和工作单位"模式,则可以使用

Additional There are few of doing this, but if you use Repostory and Unit Of Work pattern, you can use an approach like this

您将要拥有的每个DbContext,都可以与该数据库中的上下文中的一组实体相关联.像下面这样

Each DbContext you going to have, you can associate with set of entities within that database in context. Something like below

public class ProductContext : DbContext
{
    public ProductContext ()
        : base("connectionStringA")
    {
    }

    public DbSet<Product> Accounts { get; set; }
}


public class LicenceContext : DbContext
{
    public LicenceContext ()
        : base("connectionStringB")
    {
    }

    public DbSet<Licence> Licenses{ get; set; }
} 

这篇关于MVC4多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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