How do I implement DbContext inheritance for multiple databases in EF7 / .NET Core

后端 未结 3 1807
礼貌的吻别
礼貌的吻别 2020-12-14 07:58

I am building web APIs in ASP.NET Core 1.1.

I have a number different databases (for different systems) which have common base schemas for configuration items such a

3条回答
  •  失恋的感觉
    2020-12-14 08:15

    Depending on your requirements you can simply use the non type specific version of DbContextOptions.

    Change these:

    public ConfigurationContext(DbContextOptions options):base(options)    
    public InvestContext(DbContextOptions options):base(options)
    

    to this:

    public ConfigurationContext(DbContextOptions options):base(options) 
    public InvestContext(DbContextOptions options):base(options)
    

    Then if you create your ConfigurationContext first, the classes that inherit it seem to get the same configuration. It may also depend on the order in which you initialize the different contexts.

    Edit: My working example:

    public class QueryContext : DbContext
    {
        public QueryContext(DbContextOptions options): base(options)
        {
        }
    }
    
    public class CommandContext : QueryContext
    {
        public CommandContext(DbContextOptions options): base(options)
        {
        }
    }
    

    And in Startup.cs

    services.AddDbContext(options =>
                     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    services.AddDbContext(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    

    alternatively, in a test class:

        var connectionString = "Data Source=MyDatabase;Initial Catalog=MyData;Integrated Security=SSPI;";
    
        var serviceProvider = new ServiceCollection()
            .AddDbContext(options => options.UseSqlServer(connectionString))
            .BuildServiceProvider();
    
        _db = serviceProvider.GetService();
    

提交回复
热议问题