I have been carving out a section of code for a reporting app. I have derived many interfaces, for example
public interface IDateRangeSearchable
{
DateTime StartDate { get; }
DateTime EndDate { get; }
}
which I then have created helper methods to access expressions and add them, without needing to rewrite the same logic over and over, also attempting to preserve consistency and business logic in one place:
public static Expression<Func<Thingy, bool>> AddDateRangeFilterExpr<T>(this T model, Expression<Func<Thingy,bool>> webOrderItemExpr)
where T : IDateRangeSearchable
{
return webOrderItemExpr.AndAlso(thing => thing.Date >= model.StartDate && thing.Date <= model.EndDate);
}
AndAlso is a custom function that essentially combines expressions so as to avoid using multiple Where statements.
But here is the problem I see developing from this pattern:
Option 1: I have to write a custom implementation of "AddDateRangeFilterExpr" for Entity Object "Thingy1", "Thingy2, ad infinitum.
Problem: this is not dry. Probably what I will do starting out, since i am mainly concerned with 3 or 4 entity objects, and prefer duplication to the wrong abstraction. But I am looking for the right one here, since more may be added.
Option 2: I add an interface onto the Entity Object that has field "Date", and rewrite the signature.
Problem : Date fields I deal with vary.. nullable, not nullable, and can be named "Date", "DateAdded", "thingDate" etc. Meaning multiple interfaces AND implementations, clunky, not dry probably even worse..
Option 3:???
Call me crazy, but I am not an expression wizard yet. I am very interested in them though. I want to know if it is possible to transform an expression from:
Expression<Func<Thingy, DateTime?>> dateExpr = t => t.Date;
into
Expression<Func<Thingy, bool>> thingExpr = t => t.Date >= someDate;
which would allow me to just pass in the expression which would then perform that date filter on the column specified.
thingExpr = model.AddDateRangeFilterExpr(thingExpr, dateExpr);
Then i would only need an implementation for DateTime and DateTime? and some entity objects with multiple date columns, i could choose different date columns depending on what was needed.
Or in other words, can you transform a predicate(correct term?) somehow from a Date, to a boolean constructed from the column of that date field?
Sorry, I am really on the border of my knowledge here with expressions, so my language gets less precise as i tread into what I don't understand fully, I am just really here to determine if my wishful thinking could bear fruit in this direction. Open to criticisms on the whole approach as well, or resources for learning more about expressions in relation to this.