c# - 如何处理 EF 数据库优先上下文列表并正确转换它们?
问题描述
我有一个具有不同名称的实体框架的 6.0 数据库优先上下文列表。它们都包含一个名为“bill”的表。我需要检查每个数据库的账单表,并根据条件将信息添加到单个新数据库中。例子 :
Company1_Entities
Company2_Entities
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)
}
}
}
}
解决方案
最简单的解决方案是让每个上下文实现相同的接口,例如:
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.
推荐阅读
- java - 在创建 Docker 映像之前构建前端
- matlab - 找到满足条件的矩阵
- php - 在未知结尾的字符串中查找多个子字符串
- python - Fastest way for boolean matrix computations
- mongodb - MongoDB - how to update object using a field in the object
- python - How to broadcast a message to tornado socket clients all at once?
- javascript - Vue 中的 Immer 数据未更新
- javascript - Puppeteer: input field selected by ID returns undefined
- python - Is there a way to convert numbers to colours
- php - 使用 group_concat 时出现拆分数组的问题