简体   繁体   中英

Dynamically select column name using Linq to Entities (EF6)

I want to encapsulate common scenarios when using EF6. Here's an example:

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

But GetProperty can't be converted to a query. So I'm thinking on selecting dynamically the column using "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));
  }

Is this possible? Thanks in advance.

You can dynamically create a Expression<Func<T, bool>> using the Expression class like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM