【问题标题】:Entityframework 4 query entities dynamically by nameEntityframework 4 按名称动态查询实体
【发布时间】:2013-12-17 14:41:56
【问题描述】:

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

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

部门:ID、名称、代码

状态:ID 名称、代码

我必须从 xls 将数据加载到表 Orders 中,它的结构如下:代码(订单)、名称、代码(扇区)、代码(状态)。 因此,对于外键,我必须按代码查询外键 id(用于扇区和状态),然后分配给 SectorId 和 StatusId; 我有几十个字段的大表。所以我不想手动设置每个字段。 如果我知道 xls 的结构,我可以创建一个字典 Dictionary,其中键是字段的名称(在 Orders 表中),值是 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.

}

是否有可能实现以及如何实现?请帮忙!

【问题讨论】:

    标签: c# entity-framework-4


    【解决方案1】:

    没有人能帮助我,真是令人失望。答案当然是反射。 正如问题中提到的,我们可以创建一个从 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);
            }
        }
    }
    

    这东西比上百个字段一一初始化更紧凑,也有一些重用。因为对于不同的实体你只需要生成新的字典,而main函数是一样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多