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

时间:2015-07-08 19:40:52

标签: c# entity-framework linq-to-entities entity-framework-6

我想在使用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无法转换为查询。 因此,我正在考虑使用&#34; propertyName&#34;。

动态选择列
  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));
  }

这可能吗? 提前谢谢。

1 个答案:

答案 0 :(得分:6)

您可以使用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);
}