IQueryable to List

前端 未结 1 2058
长情又很酷
长情又很酷 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().ToList();
    

    Or

    public static IList CastToList(this IEnumerable source)
    {
        return new List(source.Cast());
    }
    
    var finalQuery = query.Select(string.Format("new({0})",
                                                string.Join(",", selectors)));
    var result = finalQuery.CastToList();
    

    0 讨论(0)
提交回复
热议问题