【问题标题】:How can I dynamically connect to different databases with Entity Framework 6?如何使用 Entity Framework 6 动态连接到不同的数据库?
【发布时间】:2015-02-19 12:34:33
【问题描述】:

我正在使用 WinForms 和 .NET 4.0,首先使用带有代码的 EF 6。

我需要提供连接到 MySQL 或 SQL Server 数据库的可能性。目前我在 XML app.config 文件中使用不同的连接字符串,并在 DBContext 类中更改名称。我怎样才能让它动态地工作?

【问题讨论】:

    标签: c# database winforms entity-framework ef-code-first


    【解决方案1】:
    //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; }
    }
    }
    

    检查此链接 http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多