3 回答
TA贡献1848条经验 获得超10个赞
这并不太难,但是您需要调用OrderBywith reflection,因为您事先不知道关键字段的类型。因此,鉴于您已经显示的代码,您将执行以下操作:
// Build up the property expression to pass into the OrderBy method
var parameterExp = Expression.Parameter(typeof(T), "x");
var propertyExp = Expression.Property(parameterExp, keyField);
var orderByExp = Expression.Lambda(propertyExp, parameterExp);
// Note here you can output "orderByExp.ToString()" which will give you this:
// x => x.NameOfProperty
// Now call the OrderBy via reflection, you can decide here if you want
// "OrderBy" or "OrderByDescending"
var orderByMethodGeneric = typeof(Queryable)
.GetMethods()
.Single(mi => mi.Name == "OrderBy" && mi.GetParameters().Length == 2);
var orderByMethod = orderByMethodGeneric.MakeGenericMethod(typeof(T), propertyExp.Type);
// Get the result
var sortedQueryable = (IQueryable<T>)orderByMethod
.Invoke(null, new object[] { queryable, orderByExp });
TA贡献1789条经验 获得超8个赞
与 DavidG 答案中的想法相同,但方法不同
// build lambda expression (T t) => t.KeyField
var type = typeof(T);
var parameter = Expression.Parameter(type, "k");
var lambda = Expression.Lambda(Expression.Property(parameter, keyField), parameter);
// get source expression
var baseExpression = queryable.Expression;
// call to OrderBy
var orderByCall = Expression.Call(
typeof(Queryable),
"OrderBy",
new[] {type, keyField.PropertyType},
baseExpression, lambda
);
// sorted result
var sorted = queryable.Provider.CreateQuery<T>(orderByCall);
TA贡献1816条经验 获得超6个赞
我喜欢使用具有 T 类型 Id 属性的接口 IBaseEntity。这将使您的查询:
void DoStuff<IBaseEntity>(...)
{
IQueryable<IBaseEntity> queryable = ... // given
var sortedQueryable = queryable.OrderById(e=> e.Id); //extension method
...
}
扩展方法:
public static IQueryable<IBaseEntity<T>> OrderById<T>(this IQueryable<IBaseEntity<T>> query)
{
return query.OrderBy(e => e.Id);
}
每个实体都会实现 IBaseEntity 并具有类似的东西
public partial class MyEntity : IBaseEntity<long>
{
[Required]
public override long Id
{
get { return base.Id;}
set { base.Id = value;}
}
}
然后在上下文中
modelBuilder
.Entity<MyEntity>()
.ToTable("DatabaseTable", "DatabaseSchema")
.HasKey(e => e.Id)
.Property(e => e.Id)
.HasColumnName("DatabasePrimaryKey")
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
注意:这需要在上下文和实体中进行一些设置。数据库可以具有您想要的任何键,您可以将它们单独映射到上下文的 OnModelCreating 方法中的属性 Id。
- 3 回答
- 0 关注
- 136 浏览
添加回答
举报