Entityframework 4按名称动态查询实体

时间:2013-12-17 14:41:56

标签: c# entity-framework-4

我在我的应用中使用Entity Framework 4。我有一组简单的实体,例如:

订单:Id,代码,名称,StatusId,SectorId

部门:身份证,姓名,代码

状态:Id名称,代码

我必须从xls加载数据到表订单它具有如下结构:代码(订单),名称,代码(扇区),代码(状态)。 因此,对于外键,我必须按代码(扇区和状态)查询外键id,然后分配到SectorId和StatusId; 我有几十个领域的大桌子。所以我不想手动设置每个字段。 如果我知道xls的结构我可以创建一个字典Dictionary其中key是字段的名称(在Orders表中),value是xls中列的索引。 所以我喜欢像

这样的东西
foreach(var item in Dictionary)
{

///Determine if the field is Foreign key for Entity Order (for example in ObjectContext) using GetType().GetProperty().GetValue.... or something

// If so query  ObjectContext for the id of the entity that is foreign key using a   value of Code from xls.

}

是否有可能完成以及如何实现?请帮助!

1 个答案:

答案 0 :(得分:0)

非常令人失望,没有人可以帮助我。答案当然是思考。 正如在一个问题中提到的,我们可以创建一个从xls导入的实体属性的字典,其中属性名称作为键,xls列索引作为值。 然后有一个List> importData - 在foreach循环中导入的数据遍历xls的所有行。 然后遍历字典,如果有名称匹配键的实体属性,则设置值。 应该有一些检查。但作为一个例子:

MyEntity editItem=new MyEntity();  
foreach (List<string> data in importData) //loop each xls row
{
    foreach (PropertyInfo pr in MyEntity.GetType().GetProperties())
    {
        int excelindex = -1;
            if (excelFields.Keys.Contains(pr.Name))
            {
            excelFields.TryGetValue(pr.Name, out excelindex);
            editItem.GetType().GetProperty(pr.Name).SetValue(editItem, Convert.ChangeType(data[excelindex], editItem.GetType).GetProperty(pr.Name).PropertyType), null);
        }
    }
}

这个东西比较紧凑,然后逐个启动数百个字段,还有一些重用。因为对于不同的实体,您只需要生成新的词典,而主要功能是相同的。