如何在DBContext中具有多个数据库?

时间:2019-02-07 15:38:15

标签: c# asp.net-core asp.net-core-mvc entity-framework-core

我有多个相似的数据库,并且我的ASP.Net Core 2.2 MVC应用程序具有EF DBContext,每个数据库使用不同的连接字符串。我只想在一个查询中通过DBContext从每个数据库收集TABLE1的信息。我该如何实现?

public class DBContext : DbContext
{
    private string _dbconnectionstring;

    public DBContext(string cnn)
        : base()
    {
        _dbconnectionstring = cnn;
    }

    public virtual DbSet<TABLE1> Table1 { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfiguration(new Table1Configuration());
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_dbconnectionstring);
    }
}

1 个答案:

答案 0 :(得分:0)

谢谢大家的回答。我必须更新服务才能为每个数据库做一个循环,并为每个查询累积结果,就像这样:

            if (_userService.GetDBName() == "ALL")
        {
            // If Factory selected is ALL, grab all user factories DBName in a list
            var factories = _adm.GetUserFactoriesForCombo(_userService.GetUserId()).Where(f => f.FactoryId > 0);

            // Get all PruchaseOrders from all factories
            List<PurchaseOrders> pos = new List<PurchaseOrders>();
            foreach (var f in factories)
            {
                using (var uow = new OperationsUOW(new OperationsContext(_userService.GetDBContext(f.FactoryDB)), _userService))
                {
                    var npos = uow.PurchaseOrders.GetAll();
                    pos.AddRange(npos);
                }
            }

            return pos;
        }