简体   繁体   中英

How can I dynamically connect to different databases with Entity Framework 6?

I'm working with WinForms and .NET 4.0, using EF 6 with code first.

I need to offer the possibility to connect to a MySQL or a SQL Server DB. For the moment I use different connection strings in the XML app.config file and I change the name in the DBContext class. How can I make that work dynamically instead?

//first DbContext
namespace MultiDataContextMigrations.Models
{
public class DataContext : DbContext
{
 public DataContext()
 : base("DefaultConnection")
 {

 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
 //TODO:Define mapping
 }

 public DbSet Users { get; set; }
 public DbSet Orders { get; set; }
}
}
//second DbContext
namespace MultiDataContextMigrations.Models
{
public class UserDataContext : DbContext
{
 public UserDataContext():base("DefaultConnection")
 {
 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
 //TODO:Define mapping
 }

 public DbSet Users { get; set; }
 public DbSet Roles { get; set; }
}
}

Check this Link http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM