开发者

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 sortExpress开发者_运维百科ion = 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.


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 ))
                    );


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜