我想编写一些 API 来使用 LINQ2Entities 对服务器端(SQLServer)上的实体进行排序。
我有一个包含表达式的类,表示实体的排序字段和排序方向:
public class SortOption<TEntity>
{
public SortOption(Expression<Func<TEntity, dynamic>> keySelector,
bool ascending = true)
{
KeySelector = keySelector;
Ascending = ascending;
}
public Expression<Func<TEntity, dynamic>> KeySelector { get; private set; }
public bool Ascending { get; private set; }
}
对于我的每个实体,我都有从上面继承的类。例如:
public class PostSorting: SortOption<PostEntity>
{
public PostSorting(): base(p => p.Published)
{
}
}
public class PostEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public DateTime? Published { get; set; }
public DateTime Modified { get; set; }
public string Title { get; set; }
}
主要目标是在我的存储库的方法中使用 SortOption 类的属性,该方法返回实体:
public class Repository<TEntity>
{
public IEnumerable<TEntity> List(SortOption<TEntity> sortOptions)
{
IQueryable<TEntity> query;
if (sortOptions.Ascending)
query = dbSet.OrderBy(sortOptions.KeySelector);
else
query = dbSet.OrderByDescending(sortOptions.KeySelector);
return query;
}
}
*“dbSet”字段是System.Data.Entity.DbSet<TEntity>
如果我尝试使用 PostSorting 类按类型与字符串类型不同的任何属性对实体进行排序,我会收到如下错误:
"LINQ to Entities only supports casting EDM primitive or enumeration types.".
例如(按已发布字段排序):
"Unable to cast the type 'System.Nullable`1[[System.DateTime, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type
'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."
或(如果我想按修改字段排序)
"Unable to cast the type 'System.DateTime' to type 'System.Object'.
LINQ to Entities only supports casting EDM primitive or enumeration types."
of(如果我想按 ID 字段排序)
"Unable to cast the type 'System.Guid' to type 'System.Object'.
LINQ to Entities only supports casting EDM primitive or enumeration types."
我在这个任务上工作了几天,但我找不到解决问题的答案。