是否可以从DataContext.ExecuteQuery返回IEnumerable匿名对象? [英] Is it possible to return IEnumerable of anonymous objects from DataContext.ExecuteQuery?
问题描述
我开发了一个报告引擎,其中的报告基于模板.每个模板都有带SQL查询的字符串,每个报表都有SQL查询参数的特定值.为了呈现报告,我设置了参数并调用 DataContext .ExecuteQuery 方法获取记录列表.但是要捕获返回的列,我必须知道它们的名称,并有一个具有相应属性的类.
I develop a reporting engine where reports are based on templates. Every template has string with SQL query and every report has specific values for SQL query parameters. To render a report I set parameters and call DataContext.ExecuteQuery method to get list of records. But to catch returned columns I have to know their names and have a class with corresponding properties.
是否有可能以某种方式从DataContext.ExecuteQuery返回IEnumerable匿名对象,然后使用Reflection确定它们的属性?
Is it possible somehow to return IEnumerable of anonymous objects from DataContext.ExecuteQuery and then determine their properties using Reflection?
我需要 SqlDataReader的LINQ等效项.GetValues .
谢谢!
推荐答案
在我们使用带有dynamiс关键字的C#4.0之前,我们可以使用此解决方案(文章
Until we have C# 4.0 with dynamiс keyword we can use this solution (slightly modified code from an article Executing arbitrary queries in LINQ to SQL by Octavio Hernández Leal):
public static class DataContextExtension
{
public static IEnumerable<Dictionary<string, object>> ExecuteQuery(this DataContext dataContext, string query)
{
using (DbCommand command = dataContext.Connection.CreateCommand())
{
command.CommandText = query;
dataContext.Connection.Open();
using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
dictionary.Add(reader.GetName(i), reader.GetValue(i));
yield return dictionary;
}
}
}
}
}
此扩展方法返回IEnumerable of Dictionary<>对象,其中键是查询列的名称.
This extension method returns IEnumerable of Dictionary<> objects where keys are names of query columns.
这篇关于是否可以从DataContext.ExecuteQuery返回IEnumerable匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!