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

2024-03-22

我开发了一个报告引擎,其中报告基于模板。每个模板都有带有 SQL 查询的字符串,每个报告都有 SQL 查询参数的特定值。为了呈现报告,我设置参数并调用数据上下文.执行查询 http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executequery.aspx获取记录列表的方法。但要捕获返回的列,我必须知道它们的名称并拥有一个具有相应属性的类。

是否有可能以某种方式从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable,然后使用反射确定它们的属性?

我需要一个 LINQ 等效项SqlDataReader.GetValues http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalues.aspx.

Thanks!


直到我们有了 C# 4.0dynamiс关键字我们可以使用这个解决方案(稍微修改了文章中的代码在 LINQ to SQL 中执行任意查询 http://geeks.ms/blogs/ohernandez/archive/2008/01/30/executing-arbitrary-queries-in-linq-to-sql.aspx作者:奥克塔维奥·埃尔南德斯·莱尔):

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,其中键是查询列的名称。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable? 的相关文章

随机推荐