Dynamically Linq Select Cast To IEnumerable

六眼飞鱼酱① 提交于 2019-12-12 23:53:02

问题


I'm creating a Widget builder which Dynamically takes in Queries and returns a datatable with the results. NOTE: this uses Dynamic Linq to take in string queries the library source can be found here

My only issue is casting the results set to an IEnumerable.

    public DataTable GetEntityData<D>(string Query, int NumbOfResults, List<string> Columns)
       where D : class
    {

        ObjectContext objectContext = ((IObjectContextAdapter)this).ObjectContext;

        var FDW = (objectContext.CreateObjectSet<D>() as IQueryable<D>).Where(Query).Take(NumbOfResults);

        string Column = "new(ID, ExtTitleID)";

        var res = FDW.Select(Column).Cast<object>().ToList();            

        return DataTableCaster.CreateTableObj(res);

    }

This is an attempt to cast at line

    var res = FDW.Select(Column).Cast<object>().ToList();   

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

It must be an Anonymous Type so I can grab entity related properties I CANNOT cast this to a list of string using reflection ie

         // I cannot grab the correct Properties with this
         var FD = from p in FDW.ToList()
                 select
                 (
                   (
                    from col in Columns
                    select p.GetType().GetProperty(col).GetValue(p, null).ToString()
                   ).ToList()
                 ).ToList();

the code below is unable to get subproperties of internal types.


回答1:


I overrided the Dynamic.cs Class to suppor Ienumerable select instead of Iqueryable which now will support my cast. To Override the class use this code

    public static IEnumerable<T> Select<T>(this IEnumerable source, string selector, params object[] values)
    {
        return Select(source, selector, values).Cast<T>();
    }
    public static IEnumerable Select(this IEnumerable source, string selector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (selector == null) throw new ArgumentNullException("selector");
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.AsQueryable().ElementType, null, selector, values);
        return source.AsQueryable().Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Select",
                new Type[] { source.AsQueryable().ElementType, lambda.Body.Type },
                source.AsQueryable().Expression, Expression.Quote(lambda)));
    }


来源:https://stackoverflow.com/questions/26367241/dynamically-linq-select-cast-to-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!