I have a little odd question working by lifting an very old system and replacing 10year old nHibernate with EF. I have trouble formulating some linq extensions for a search page. The thing I want to refactor is this(this code rows is used many times or with a variant for other types) :
if (searchCriteria.PlannedEndDateFrom.HasValue && searchCriteria.PlannedEndDateTo.HasValue)
{
efquerable= efquerable.Where(d => searchCriteria.PlannedEndDateFrom < d.PlannedEndDate && d.PlannedEndDate > searchCriteria.PlannedEndDateTo);
}
else if (searchCriteria.PlannedEndDateFrom.HasValue)
{
efquerable= efquerable.Where(d => d.PlannedEndDate > searchCriteria.PlannedEndDateFrom);
}
else if (searchCriteria.PlannedEndDateTo.HasValue)
{
efquerable= efquerable.Where(d => d.PlannedEndDate < searchCriteria.PlannedEndDateTo);
}
This should be able to move to an extensions where I do this kind of checks instead...
private static IQueryable<T> FilterOnCorrectSearchDateTime<T>(this IQueryable<T> efquerable, Expression<Func<T, DateTime>> datePropertyName, DateTime? dateFrom, DateTime? dateTo)
{
//Missing code
}
And then be called like
EFquerable = EFquerable.FilterOnCorrectSearchDateTime<EntityObjectWithDatetimeproperty>(s=>s.PlannedEndDate ,searchCriteria.PlannedEndDateFrom,searchCriteria.PlannedEndDateTo);
Any suggestions for how to solve this? What I get stuck on is to handle the checks on the properties that is sent into the function. How do I formulate the Expression<Func<T, DateTime>> datePropertyName to a usable statement for the Where function ? Is there something else I have missed in thinking in this refactoring? I have tought on using System.Linq.Dynamics but that seems less good...