Dynamically select column name using Linq to Entities (EF6)

c# entity-framework entity-framework-6 linq-to-entities

Question

I want to encapsulate typical EF6 use cases. Here's an illustration:

   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, however, cannot be transformed into a query. I'm considering utilizing "propertyName" to dynamically choose the column.

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

Can this be done? I appreciate it.

1
3
7/8/2015 8:56:39 PM

Accepted Answer

Dynamically developing aExpression<Func<T, bool>> employing the Expression class as follows:

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);
}
6
7/8/2015 9:35:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow