简体   繁体   中英

How to deal with a list of EF database first contexts and cast them correctly?

I have a list of entity framework's 6.0 database first contexts with different names. They all contain a table named "bill". I need to check in every database's bill table, and add informations into a single new database depending on a condition. Example :

  1. Company1_Entities
  2. Company2_Entities
  3. Company3_Entities

These 3 databases contain the bill table. I need to store these bill conditionnaly into :

All_Bills_Entities

As the number of company will grow, I need to make this dynamic. I was thinking of something like this :

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)
           }
        }
    }
}

The easiest solution is to make each context implement the same interface, for example:

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

Now make your contexts implement it:

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

    //etc...
}

And finally, change your list to use the interface:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM