我开发了一个报告引擎,其中报告基于模板。每个模板都有带有 SQL 查询的字符串,每个报告都有 SQL 查询参数的特定值。为了呈现报告,我设置了参数并调用 DataContext.ExecuteQuery获取记录列表的方法。但是要捕获返回的列,我必须知道它们的名称并有一个具有相应属性的类。
是否有可能以某种方式从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable,然后使用反射确定它们的属性?
我需要 SqlDataReader.GetValues 的 LINQ 等效项.
谢谢!
最佳答案
直到我们有了带有 的 C# 4.0动态 我们可以使用这个解决方案的关键字(对 Octavio Hernández Leal 的文章 Executing arbitrary queries in LINQ to SQL 中的代码稍作修改):
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;
}
}
}
}
}
此扩展方法返回 Dictionary<> 对象的 IEnumerable,其中键是查询列的名称。
关于linq - 是否可以从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863030/