I have various types of EF entities, all of them have a navigation property called "Employee". When generating reports the user will have the option to filter the report according to the different employee properties (Cost Center, gender, etc.).
Something like this:
var courses = context.Courses
.Where(c => c.Employee.CostCenterID == ccID
&& c.Employee.Rank == rankID
....
)
.ToList();
The real filter code is much more longer but this was just a hint. Anyway, I figured out an easier way of doing this filtering with an extension method using an interface:
public interface IFilterable
{
Employee Employee
{
get;
set;
}
}
Then, I added partial classes to inherit the previous interface for different entities that has the Employee
navigation property, for example:
public partial class Course: IFilterable
{
}
Then created the following generic method:
public static IQueryable<T> Filter<T>(this IQueryable<T> source, SearchCriteria sc)
where T : class, IFilterable
{
var filtered = source.Where(e => e.Employee.CostCenterID == sc.CostCenterID
&& e.Employee.Gender == sc.Gender
.....
);
return filtered;
}
then simply I can use it like this on any class that inherits IFilterable
:
var list = context.Courses.Filter(sc).ToList();
Note: the SearchCriteria
is just a simple class that holds different employee properties.
Q: Is this the way to do it? or is there a more elegant way?