如何从动态linq查询中检索结果,将来自后期绑定库的数据转换为数据表?

时间:2014-12-11 21:34:30

标签: c# linq lambda dynamic-linq system.data.datatable

我正在开发一个自动生成报告的库。报告永远不会在高级中知道,但在Oracle数据库中配置它们的调用方式。每份报告都有自己的课程;在每个类中,都有一个返回DataTable的数据库查询。

报告生成过程很有效,但我需要为每个创建一个报告索引文件。配置也可以在数据库中找到,并具有以下格式:

  

REPORT_ID / QUERY / ELEMENT_NAME

     
   12 GROUPBY    Reference    
   12 GROUPBY    Internal_Seq 
   12 COUNT      Item_Count   
   12 MIN        Process_Date 
   12 MAX        Job_Id       
   12 SUM        Paid_Amount
  

由于每个报告都有不同的配置,我需要动态查询数据表的内容。就在那时,我看到了来自ScottGu's BlogHelp with Dynamic Linq Query的信息,让我到达了我需要的地方。我确实修改了一些代码以满足我的需求,但这就是我所拥有的:

    public void GetIndexData(DataTable p_Table)
    {
        string location = Utilities.GetLocation(this.GetType(), MethodBase.GetCurrentMethod());
        m_log.Info(location + "Starting...");

        try
        {
            //Create the datatable to contain the fields/aggregates from the datasource
            if (m_Fields.Count > 0)
            {
                List<ArchiveField> groupFields = new List<ArchiveField>();
                List<ArchiveField> aggreFields = new List<ArchiveField>();

                foreach (ArchiveField _field in m_Fields)
                {
                    if (_field.Query == "GROUPBY")
                    {
                        groupFields.Add(_field);
                    }
                    else
                    {
                        aggreFields.Add(_field);
                    }
                }

                //Build the GroupBy parameters using an anonymous type
                List<string> fields = new List<string>();
                object[] param = new object[groupFields.Count];
                int counter = 0;
                foreach (ArchiveField _field in groupFields)
                {
                    fields.Add("get_Item(@" + counter.ToString() + ") as " + _field.Name);
                    param[counter] = _field.Name;
                    counter++;
                }
                var query = p_Table.AsEnumerable().AsQueryable().GroupBy("New(" + string.Join(",", fields.ToArray()) + ")", "it", param);
                var groupType = query.ElementType;

                //Build the Select parameters using Dynamic Lambda invocation
                fields = new List<string>();
                param = new object[aggreFields.Count];
                counter = 0;
                foreach (ArchiveField _field in aggreFields)
                {
                    fields.Add("@" + counter.ToString() + "(it) as " + _field.Name);
                    param[counter] = GetGroupByExpression(groupType, _field.Name, typeof(long), _field.Query);
                    counter++;
                }
                foreach (ArchiveField _field in groupFields)
                {
                    fields.Add("it.Key." + _field.Name + " as " + _field.Name);
                }
                query = query.Select("New(" + string.Join(",", fields.ToArray()) + ")", param);

                //Convert the IQueryable to a datatable
                PropertyInfo[] _props = query.ElementType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

                DataTable dt = new DataTable();
                foreach (PropertyInfo p in _props)
                {
                    dt.Columns.Add(p.Name, p.PropertyType);
                }

                foreach (var l in query)
                {
                    var temp = l;
                    dt.Rows.Add(_props.Select((PropertyInfo p) => p.GetValue(temp, null)).ToArray());
                }                    

                m_DataSource = dt;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            m_log.Info(location + "Ending...");
        }
    }

    private LambdaExpression GetGroupByExpression(Type p_groupType, string p_ColumnName, Type p_ColumnType, string p_Aggregate)
    {
        MethodInfo fieldMethod = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(string) });
        fieldMethod = fieldMethod.MakeGenericMethod(p_ColumnType);

        ConstantExpression colParam = Expression.Constant(p_ColumnName, typeof(string));
        ParameterExpression rowParam = Expression.Parameter(typeof(DataRow), "r");
        MethodCallExpression fieldMethodCall = Expression.Call(fieldMethod, rowParam, colParam);

        var columnExpression = Expression.Lambda(fieldMethodCall, rowParam);
        ParameterExpression groupParam = Expression.Parameter(p_groupType, "g");

        MethodInfo aggrMethod = null;
        MethodCallExpression aggrMethodCall = null;
        if (p_Aggregate.ToUpper() == "COUNT")
        {
            aggrMethod = typeof(Enumerable).GetMethods().Single(m => m.Name.ToUpper() == p_Aggregate.ToUpper() & m.IsStatic & m.GetParameters().Length == 1);
            aggrMethod = aggrMethod.MakeGenericMethod(typeof(DataRow));

            aggrMethodCall = Expression.Call(aggrMethod, groupParam);
        }
        else
        {
            aggrMethod = typeof(Enumerable).GetMethods().Single(m => m.Name.ToUpper() == p_Aggregate.ToUpper() & m.ReturnType.Equals(p_ColumnType) & m.IsGenericMethod);
            aggrMethod = aggrMethod.MakeGenericMethod(typeof(DataRow));

            aggrMethodCall = Expression.Call(aggrMethod, groupParam, columnExpression);
        }

        return Expression.Lambda(aggrMethodCall, groupParam);
    }

在代码中,m_DataSource被定义为我的类中的DataTable,它应包含最终结果。

这是Microsoft的System.Linq.Dynamic类的摘录:

    public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");
        LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
        LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "GroupBy",
                new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
                source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
    }

    public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");
        LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
        LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "GroupBy",
                new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
                source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
    }

我的代码在此部分失败,只要它试图找到查询对象的元素,就会出现“指定的强制转换无效”错误:

                foreach (var l in query)

我需要一个解决方案,知道:

  1. 我必须在Framework 3.5中工作(没有机会改变它)。
  2. 所有调用都是动态的,因为报告类是通过后期绑定调用的,我从来不知道要使用哪个聚合(配置从一个报告更改为下一个报告)。
  3. 我必须限制第三方库的数量。如果一切都可以在我的代码中完成而没有外部影响,那就更好了。
  4. 我无法访问数据库以使用聚合生成辅助查询,因为数据来自报告类。
  5. 我缺少什么来获取数据表所需的值?原始示例是否有缺陷,因此无法找到可以枚举我需要的数据流的演员?

0 个答案:

没有答案