同时在EntityFramework.Core中对多个连接/数据库(SQLite | Postgres)使用相同的DbContext类

时间:2019-02-08 11:08:46

标签: c# dependency-injection entity-framework-core

这个问题之前曾被问过几次,但我找不到任何对我有帮助的解决方案。

我有两个不同的数据库(SQLitepostgres),它们具有相同的DbContextTranslationContext)。

我想“打开”两个数据库并互相读/写。

我需要帮助时遇到以下问题:

  • 如何配置依赖项注入(StructureMap
  • 如何通过IDbContextScopeFactory
  • 获取不同的上下文

依赖注入

如何区分它们?是否可以给他们一个实例名称,例如localremote

c.For<DbContextOptions<TranslationContext>>().Use(
    new DbContextOptionsBuilder<TranslationContext>()
    .UseNpgsql(new NpgsqlConnectionStringBuilder
    {
        Host = "10.11.12.13",
        Username = "fooUser",
        Password = "fooPw",
        Port = 5432,
        Database = "Translations",
        PersistSecurityInfo = true

    }.ConnectionString).Options);

c.For<DbContextOptions<TranslationContext>>().Use(
    new DbContextOptionsBuilder<TranslationContext>()
        .UseSqlite("Data Source= fooFilePath")
        .Options);

使用IDbContextScopeFactory

这是我使用IDbContextScopeFactory的正常方法。但是到目前为止,我一直有不同的DbContext并且没有问题。

using (var scope = contextScopeFactory.Create())
{
    var translations = scope.DbContexts.Get<TranslationContext>().Translations;

    // How to get the sqlite and how to get the postgres context?

}

TranslationContext

public class TranslationContext : DbContext
{
    public DbSet<DbTextTranslation> Translations { get; set; }

    public TranslationContext(DbContextOptions<TranslationContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("public");

        // use lower case columns
        modelBuilder.ApplyConfiguration(new DbTextTranslation.DbConfiguration());
        base.OnModelCreating(modelBuilder);
    }        
}

0 个答案:

没有答案