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.
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.
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.
UPDATE :
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
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; }
}