Dynamically Linq Select Cast To IEnumerable

c# dynamic-linq linq reflection

Question

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
1
10/14/2014 5:58:20 PM

Accepted Answer

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)));
    }
0
10/14/2014 8:00:40 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow