简体   繁体   中英

EF Core 3 filtering data with Extension method

I am trying to make extension method for querying ef core. I have this Extension:

 public static class FiltrExtension
  {
     public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter) 
     {
      if (!string.IsNullOrWhiteSpace(filter.OrderType))
         query.Where(x => x.OrderType == filter.OrderType);
      return query;
     }
  }

and then I am trying to filtr data, but the extension method doing nothing:

var data = await _uow.DatabaseContext.Contract.Filtr(filter).ToListAsync();

Can anybody help please?

You should put the result of query.Where(x => x.OrderType == filter.OrderType);into query like this

public static class FiltrExtension
  {
     public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter) 
     {
      if (!string.IsNullOrWhiteSpace(filter.OrderType))
        query = query.Where(x => x.OrderType == filter.OrderType);
      return query;
     }
  }

You have to return the results:

public static class FiltrExtension
  {
     public static IQueryable<Contract> Filtr(this IQueryable<Contract> query, OrderFilter filter) 
     {
      if (!string.IsNullOrWhiteSpace(filter.OrderType))
         var result = query.Where(x => x.OrderType == filter.OrderType);
      return result;
     }
  }

You can user regular expressions:

  public static IQueryable<Contract> And<Contract>(this IQueryable<Contract> source, Expression<Func<Contract, bool>> predicate)
    {   
      return source.Where(predicate);    
    }

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