使用Linq to Entities (EF6)动态选择列名

本文关键字:动态 选择 EF6 Linq to Entities 使用 | 更新日期: 2023-09-27 18:01:36

我想封装使用EF6时的常见场景。下面是一个例子:

   public class StringRequest : DbRequestProperty
   {
      public string Name { get; set; }
      public bool? ExactMatch { get; set; }
      protected override bool IsValid()
      {
         return !string.IsNullOrWhiteSpace(Name);
      }
      private bool RequestExactMatch()
      {
         return ExactMatch.HasValue && ExactMatch.Value;
      }
      protected override IQueryable<T> Execute<T>(IQueryable<T> original, string propertyName)
      {
         return RequestExactMatch()
            ? original.Where(o => GetProperty<string>(o, propertyName) == Name)
            : original.Where(o => GetProperty<string>(o, propertyName).Contains(Name));
      }
   }

但是GetProperty不能转换为查询。所以我在考虑动态选择列使用"propertyName"。

  protected override IQueryable<T> Execute<T>(IQueryable<T> original, string propertyName)
  {
     return RequestExactMatch()
        ? original.Where(o => GetColumnByName<string>(propertyName) == Name)
        : original.Where(o => GetColumnByName<string>(propertyName).Contains(Name));
  }

这可能吗?

使用Linq to Entities (EF6)动态选择列名

您可以使用Expression类动态地创建Expression<Func<T, bool>>,如下所示:

protected override IQueryable<T> Execute<T>(IQueryable<T> original, string propertyName)
{
   var parameter = Expression.Parameter(typeof(T));
   var property = Expression.PropertyOrField(parameter, propertyName);
   var constant = Expression.Constant(Name);
   Expression predicate;
   if(RequestExactMatch())  
   {     
      predicate = Expression.Equal(property, constant);    
   }
   else 
   {
      predicate = Expression.Call(property, "Contains", null, constant);    
   }
   var lambda = Expression.Lambda<Func<T, bool>>(predicate, parameter);
   return original.Where(lambda);
}