简体   繁体   中英

Unable to cast the type 'System.DateTime' to type 'System.Object' in LINQ to Entities

I have the following code:

public static IQueryable<T> ApplyOrdering<T>(this IQueryable<T> query, IQueryObject queryObject, Dictionary<string, Expression<Func<T, Object>>> columnsMap)
    {
        if (String.IsNullOrWhiteSpace(queryObject.SortBy) || !columnsMap.ContainsKey(queryObject.SortBy))
            return query;

        if (queryObject.IsSortAscending)
            return query.OrderBy(columnsMap[queryObject.SortBy]);
        else
            return query.OrderByDescending(columnsMap[queryObject.SortBy]);
    }

But I get the following error if object in the dictionary is a date:

Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

This the code for the columnsMap that I pass through to call the above extension method:

  var columnsMap = new Dictionary<string, Expression<Func<Post, Object>>>
  {
            ["createdDate"] = p => p.CreatedDate
  };

  query = query.ApplyOrdering(queryObject, columnsMap);

How can I fix?

I think that the problem is in Expression<Func<T, Object>>> columnsMap

DateTime isn't a class, is a struct so if your signature wait for an Object and you pass a primitive type, it throws the exception.

However, I don't know how to fix it, at this moment.

it probably cause of Expression<> , you should be using Func<> . have a look at my answer.

https://stackoverflow.com/a/52030539/7369310

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM