Ganator
Ganator

Reputation: 179

Unable to cast the type 'System.String' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types

I am using EF 4 but it is giving me error when I try to order my list.

Unable to cast the type 'System.String' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.

This is my code to get the experssion by entering the property name, example below get the Customer Name

var param = Expression.Parameter(typeof(Customer), "N");

var sortExpression = Expression.Lambda<Func<T, object>>
            (Expression.Convert(Expression.Property(param, "Name"), typeof(object)), param);

And my EF code is

GetObjectSet<T>().AsQueryable().OrderBy(sortExpression).Skip(0).Take(5);

I know it is some sort of casting problem with EF because it works without the EF but it gives me this error when i hook it up with EF. Is there a work around or something because i don't want to use LINQ.

Upvotes: 3

Views: 3689

Answers (3)

Ignacio Franco
Ignacio Franco

Reputation: 136

I had the same problem, and the method that solved it was:

using System; 
 using System.Collections.Generic; 
 using System.Linq; 
 using System.Linq.Expressions; 


public class GenericSorter<T> {
public IEnumerable<T> Sort(IEnumerable<T> source, string sortBy, string sortDirection)
{
    var param = Expression.Parameter(typeof(T), "item");

    var sortExpression = Expression.Lambda<Func<T, object>>
        (Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param);

    switch (sortDirection.ToLower())
    {
        case "asc":
            return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
        default:
            return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);

    } 
}

}

Then you can call it when you perform the query as:

var entity = nameof(DBOEntity.Property);
var order = "asc";
var query = dc.EntityDataSet.AsExpandable().OrderByDynamic(entity, order);

I hope this helps you!

Upvotes: 0

Haobo
Haobo

Reputation: 473

I've encountered the same problem, and solved by the following code:

IQueryable<T> result = DbSet.AsQueryable<T>();
var classPara = Expression.Parameter(typeof(T), "t");
var pi = typeof(T).GetProperty(sortPara);
result = result.Provider.CreateQuery<T>(
                    Expression.Call(
                        typeof(Queryable),
                        "OrderBy",
                        new Type[] { typeof(T), pi.PropertyType },
                        result.Expression,
                        Expression.Lambda(Expression.Property(classPara , pi), classPara ))
                    );

Upvotes: 1

Stephen Cleary
Stephen Cleary

Reputation: 456322

I believe this answer addresses what you're trying to do in the easiest possible way.

Upvotes: 0

Related Questions