Ale*_*yev 4 linq anonymous-types linq-to-sql
我开发了一个报告引擎,其中报告基于模板。每个模板都有带有 SQL 查询的字符串,每个报告都有 SQL 查询参数的特定值。为了呈现报告,我设置了参数并调用DataContext.ExecuteQuery方法来获取记录列表。但是要捕获返回的列,我必须知道它们的名称并有一个具有相应属性的类。
是否有可能以某种方式从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable,然后使用反射确定它们的属性?
我需要SqlDataReader.GetValues的 LINQ 等效项。
谢谢!
直到我们有了带有dynami 的C# 4.0 ?关键字我们可以使用这个解决方案(从Octavio Hernández Leal的文章Executing任意查询在 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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
此扩展方法返回 Dictionary<> 对象的 IEnumerable,其中键是查询列的名称。
| 归档时间: |
|
| 查看次数: |
8284 次 |
| 最近记录: |