linq - 是否可以从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable?

标签 linq linq-to-sql anonymous-types

我开发了一个报告引擎,其中报告基于模板。每个模板都有带有 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/

相关文章:

c# - Linq to XML 查询

c# - 查询嵌套列表

c# - 抛出新的 NotImplementedException()

C# Linq 查询不工作

c# - Linq To Sql 一对多

c# - c# 中的匿名类型是否可以通过反射访问?

c# - 查询包含对在不同数据上下文中定义的项目的引用

c# - LINQ 模型的问题 - 无法将 NULL 分配给可空 bool 值!

C++ 匿名结构指针赋值

c# - 在linq查询中设置匿名类型动态对象的所有属性