簡體   English   中英

如何處理EF數據庫優先上下文列表並正確轉換它們?

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

我有一個使用不同名稱的實體框架的6.0數據庫優先上下文列表。 它們都包含一個名為“ bill”的表。 我需要檢入每個數據庫的賬單表,並根據情況將信息添加到單個新數據庫中。 范例:

  1. Company1_Entities
  2. Company2_Entities
  3. Company3_Entities

這3個數據庫包含帳單表。 我需要有條件地將這些帳單存儲到:

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

最簡單的解決方案是使每個上下文實現相同的接口,例如:

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>();

另外,如果您知道類型,則可以使用Set<T>屬性。 例如,假設實體類型為Bill

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

當然,如果您將沒有此DbSet的實體添加到字典中,則這將在運行時失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM