C#表达式按键字段对通用查询进行排序

时间:2019-03-25 16:26:25

标签: c# linq linq-expressions

我有一个通用方法,其中我想按其关键字字段对IQueryable<T>进行排序(可以放心地假设只有一个)。因此:

void DoStuff<T>(...) 
{
   IQueryable<T> queryable = ... // given
   PropertyInfo keyField = ... // given
   var sortedQueryable = queryable.OrderBy(<some expression here>);
   ...
}

我如何定义Expression并返回keyField的{​​{1}}属性,这样才能正常工作?

3 个答案:

答案 0 :(得分:8)

这不太困难,但是您需要提前反射调用OrderBy,因为您不提前知道键字段的类型。因此,鉴于已经显示的代码,您将执行以下操作:

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

答案 1 :(得分:1)

我喜欢使用具有I类型为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。

答案 2 :(得分:1)

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