IQueryable to List

前端 未结 1 2054
长情又很酷
长情又很酷 2021-02-15 18:17

I\'m using System.Linq.Dynamic to allow me to dynamically select a list of fields from a query like this:

finalQuery = query.Select(string.Format(\"new({0})\", s         


        
相关标签:
1条回答
  • 2021-02-15 19:02

    This appears to be a limitation in the way LINQ to Entities translates IQueryable.Cast with anonymous types. You can work around this by using it as an IEnumerable (your working example does this). 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. E.g.

    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>();
    
    0 讨论(0)
提交回复
热议问题