[英]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. 我有一个使用不同名称的实体框架的6.0数据库优先上下文列表。 They all contain a table named "bill".
它们都包含一个名为“ bill”的表。 I need to check in every database's bill table, and add informations into a single new database depending on a condition.
我需要检入每个数据库的账单表,并根据情况将信息添加到单个新数据库中。 Example :
范例:
Company1_Entities
Company2_Entities
Company3_Entities
These 3 databases contain the bill table. 这3个数据库包含帐单表。 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. 另外,如果您知道类型,则可以使用
Set<T>
属性。 For example assuming the entity type is Bill
: 例如,假设实体类型为
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. 当然,如果您将没有此DbSet的实体添加到字典中,则这将在运行时失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.