Eliminating Duplication of Where Expressions in Application

Assume you have products and categories. A client says that it is necessary to use other business processes for the categories with the rating value higher than 50. You have a solid experience and you understand that tomorrow this value may be different – 127.37. As you want to avoid this situation, you write the code in the following way:

Unfortunately, this will not work if you need to select products from the corresponding categories. NiceRating has the Expression<Func<Category, bool>> type. In the case of Product, you will need to use Expression<Func<Product, bool>>.

Thus, we need to convert Expression<Func<Category, bool>> into Expression<Func<Product, bool>>.

Luckily, it is quite easy!

This is the implementation of statement composition in LinqKit. However, Entity Framework does not work with InvokeExpression and throws NotSupportedException. Do you know that LINQ has drawbacks? To work around this restriction, in LinqKit we use an extension method AsExpandable. Pete Montgomery described this issue in his blog. His version of Predicate Builder works both for IEnumerable<T> and IQueryable<T>.

Here is the code as is.

 

Max Arshinov

Max Arshinov

Chief Executive Officer (CEO) at hightech.today
Max Arshinov has been developing applications for business for more than 10 years. He had been a developer, PM, and head of the testing department until he set up his own company "Hightech". Now, Maxim is a CEO of the company.
Max Arshinov

Latest posts by Max Arshinov (see all)

Max Arshinov

Max Arshinov has been developing applications for business for more than 10 years. He had been a developer, PM, and head of the testing department until he set up his own company "Hightech". Now, Maxim is a CEO of the company.