首页 > 解决方案 > 如何处理 EF 数据库优先上下文列表并正确转换它们?

问题描述

我有一个具有不同名称的实体框架的 6.0 数据库优先上下文列表。它们都包含一个名为“bill”的表。我需要检查每个数据库的账单表,并根据条件将信息添加到单个新数据库中。例子 :

  1. Company1_Entities
  2. Company2_Entities
  3. Company3_Entities

这 3 个数据库包含 bill 表。我需要将这些账单有条件地存储到:

All_Bills_Entities

随着公司数量的增长,我需要使这种动态化。我在想这样的事情:

Dictionary<string, DbContext> lstDB = new Dictionary<string, DbContext>();

// I'm supposed to retrieve these db names from a table, but now i'm just testing

lstDB.Add("00439837", new DbContext("Company1_Entities"));
lstDB.Add("00439832", new DbContext("Company2_Entities"));
lstDB.Add("00439839", new DbContext("Company3_Entities"));

using (All_Bills_Entities main_db = new All_Bills_Entities())
{
    foreach(var dataBaseInfo in lstDB)
    {
        DbContext currentDB = dataBaseInfo.Value;

        foreach (var record in currentDB.bill.ToList()) // this does not compile, there is no bill table found here
        {
           if(record.merchant == dataBaseInfo.Key /* && other Conditions */)
           {
                main_db.bill.Add(record)
           }
        }
    }
}

标签: c#entity-frameworkdynamic

解决方案


最简单的解决方案是让每个上下文实现相同的接口,例如:

public interface IBillContext
{
    DbSet<Bill> bill { get; } 
}

现在让你的上下文实现它:

public class Company1_Entities : IBillContext
{
    public DbSet<Bill> bill { get; set; }

    //etc...
}

最后,更改您的列表以使用该界面:

Dictionary<string, IBillContext> lstDB = new Dictionary<string, IBillContext>();

Alternatively, if you know the type you can make use of the Set<T> property. For example assuming the entity type is Bill:

foreach (var record in currentDB.Set<Bill>().ToList())
{
   if(record.merchant == dataBaseInfo.Key /* && other Conditions */)
   {
        main_db.bill.Add(record)
   }
}

Of course this would fail at runtime if you added an entity to the dictionary that didn't have this DbSet.


推荐阅读