【问题标题】:How do i obtain foreign table field using string value for fieldname with reflection and entity framework如何使用带有反射和实体框架的字段名的字符串值获取外部表字段
【发布时间】:2013-10-24 10:06:22
【问题描述】:

我有 2 张桌子。使用外键链接到设备表的资产表。

要获取资产的 device_name 字段,我会在 linq 中使用:

dim device as string = result.device.device_name

Result 对象包含来自早期 linq to entity 框架命令的唯一记录。

现在我需要允许最终用户在报告中指定他们想要的字段。我最终会得到一个字段的字符串名称,所以尝试使用反射

dim name as string = result.GetType().GetProperty("asset_name").GetValue(result)

这会返回asset_name 字段,所以我觉得很好,我应该能够获得相关的外部表字段值。

dim device = result.GetType().GetProperty("device").GetValue(result).GetType.GetProperty("device_name").GetValue(result.device)

这可行,但是我必须指定对象。由于我将有其他表链接到第一个表,我是否必须编写额外的代码来检查什么对象并手动指定?还是我错了?任何帮助和建议表示赞赏。

【问题讨论】:

    标签: sql vb.net linq entity-framework reflection


    【解决方案1】:

    我找不到更清洁的解决方案,所以我就是这样做的:

    dim field as string ="device.device_name" 
    dim output as string =""
    dim subtable as string ="" 
    
    If field.Contains(".") Then 
        subtable = field.Substring(0, field.IndexOf(".")) 
        field = field.Substring(field.IndexOf(".") + 1)
    End If
    If subtable <> "" Then
      Select case subtable
        Case "device" 
            If Not IsNothing(result.device.GetType().GetProperty(field)) Then
                output = result.device.GetType().GetProperty(field).GetValue(result.device)
            End If
      End Select
    Else
        If Not IsNothing(result.GetType().GetProperty(field)) Then 
            output= result.GetType().GetProperty(field).GetValue(reult)
        End If
    End If
    Return output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多