简体   繁体   English

可以列出的IQueryable

[英]IQueryable to List

I'm using System.Linq.Dynamic to allow me to dynamically select a list of fields from a query like this: 我正在使用System.Linq.Dynamic允许我从查询中动态选择字段列表,如下所示:

finalQuery = query.Select(string.Format("new({0})", string.Join(",", selectors)));

Where selectors is just a List<string> with all the fields I want. selectors只是一个List<string> ,包含我想要的所有字段。 This works great, but this version of the extension method Select returns an IQueryable . 这很好用,但是这个版本的扩展方法Select返回一个IQueryable Not this is not IQueryable<T> . 不是 IQueryable<T> If I have an IQueryable<T> I can simply do a .ToList() to convert it into a list and force the query to actually run on the database, but with the non-generic IQueryable , that method doesn't exists. 如果我有一个IQueryable<T>我可以简单地执行.ToList()将其转换为列表并强制查询实际在数据库上运行,但是使用非泛型IQueryable ,该方法不存在。

This is because ToList is inherited from IEnumerable<T> which IQueryable<T> inherits and IQueryable , obviously, doesn't. 这是因为ToList继承自IEnumerable<T>IQueryable<T>继承而且IQueryable显然不会。

So what's the most efficient way to get an IQueryable to execute the query and give me back a list? 那么,获得IQueryable执行查询并给我一个列表的最有效方法是什么? I can do this: 我可以做这个:

List<object> rtn = new List<object>();
foreach (var o in finalQuery)
{
    rtn.Add(o);
}

But it seems like their ought to be an easier way. 但似乎他们应该是一个更容易的方式。

Edit: In response to suggestions, I tried both: 编辑:为了回应建议,我尝试了两个:

finalQuery.Cast<object>().ToList();

and: 和:

finalQuery.Cast<dynamic>().ToList();

Which both give NotSupportedExceptions with the message: 这两个都给NotSupportedExceptions提供了消息:

Unable to cast the type 'DynamicClass1' to type 'System.Object'. LINQ to Entities 
only supports casting EDM primitive or enumeration types.

This appears to be a limitation in the way LINQ to Entities translates IQueryable.Cast with anonymous types. 这似乎是LINQ to Entities使用匿名类型转换IQueryable.Cast的方式的限制。 You can work around this by using it as an IEnumerable (your working example does this). 您可以通过将其用作IEnumerable来解决此问题(您的工作示例IEnumerable )。 This causes the code to do the cast in the .NET runtime after it's retrieved from the DB, instead of trying to handle it in the DB engine. 这会导致代码在从数据库中检索在.NET运行时执行转换,而不是尝试在数据库引擎中处理它。 Eg 例如

IEnumerable finalQuery = query.Select(string.Format("new({0})",
                                                   string.Join(",", selectors)));
var result = finalQuery.Cast<dynamic>().ToList();

Or 要么

public static IList<T> CastToList<T>(this IEnumerable source)
{
    return new List<T>(source.Cast<T>());
}

var finalQuery = query.Select(string.Format("new({0})",
                                            string.Join(",", selectors)));
var result = finalQuery.CastToList<dynamic>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM