尝试在EF

时间:2016-03-24 09:24:16

标签: c# entity-framework linq

让我作为序言,我已经搜索了这个问题并尝试了很多东西,但我显然遗漏了一些简单的东西(我认为)。

我相信我的解决方案会涉及反思,但我无法做到正确。

修改: 更快的问题 - 我需要用字符串替换查询结果的.fieldname。因此var value = stops.First().con_name; .con_name在运行时需要是动态的。

基础: 我正在创建从数据库生成自定义报告的功能,其中报告布局存储在列名,列位置和字段名称表中。

以下是一份非常简单的报告的数据:

record 1
col_index  - 17
field_name - con_name

record 2
col_index -  18
field_name-  con_city

我需要查询一个名为stop_details的表,查找要包含在报告中的记录集合。

然后我想查询一个名为report_matrix的表,它将返回上述记录(我给出的两个样本记录)。

然后我需要逐步完成矩阵结果并根据数据创建列。

挑战是在运行时替换field_name。 因此,在第一次运行的下面的代码中,第二次将var value = stops.First().con_name;。{#}替换为.con_city等等。

这是我的代码:

     //get collection of stops for export

        var stops = (from s in db.stop_details 
                     where s.eCourier_export_flag == true 
                     select s)
                     .ToArray();

        //pull in all the report format details

        var reportLayout = (from r in db.report_matrix 
                            where r.report_id == 1 
                            select r)
                            .ToArray();

        //just do one line

        foreach (var layoutElement in reportLayout)
        {                
            // Select the PropertyInfo of the column.
            PropertyInfo propertyInfo = 
              stops.First().GetType().GetProperty(layoutElement.field_name);
            // name = stops.GetValue(propertyInfo, null).ToString();
            // HERE is where I need to replace .con_name with the field name from the query
            var value = stops.First().con_name; 
         }

提前感谢您的帮助.... 乔

1 个答案:

答案 0 :(得分:1)

您需要使用GetValue的{​​{1}}方法:

PropertyInfo