I started to use expressions to encapsulate business logic and be able to pass it to EF directly. However I can't figure out how to "nicely" combine and/or reuse expressions in another expressions. For example, I have the following 2 business rules for valid products and clearance products:
internal static Expression<Func<Product, bool>> fnValidProduct = (p) =>
p.DoNotDisplayProductsOnSite == false &&
p.CategoryId != null
internal static Expression<Func<Product, bool>> fnClearanceProduct = (p) =>
(p.ProductFlags & ProductFlags.Clearance) > 0 && p.Qty > 3;
However, I cannot figure out how to make a rule for "valid clearance products" using these building block. Code below won't compile for expressions:
internal static Expression<Func<Product, bool>> fnValidClearanceProduct = (p) =>
fnValidProduct(p) &&
fnClearanceProduct(p);
I've looked into this sometime ago, and I even recovered some codes which I can't really understand now - which really defies the purpose of combining expressions:
internal static Expression<Func<ProductContainer, bool>> fnValidProduct
{
get
{
var parameterExpression = Expression.Parameter(typeof(ProductContainer));
var propertyOrField = Expression.PropertyOrField(parameterExpression, nameof(ProductContainer.product));
var combined = Expression.Lambda<Func<ProductContainer, bool>>(Expression.Invoke(fnValidProduct, propertyOrField),
parameterExpression);
return combined.Expand();
}
}
Question is then - is there a way or NuGet libraries or something - to achieve that "code reuse"?