Generic Filtering Method for Linq-EF Queries

I have various types of EF objects, all have a navigation property called "Employee". When creating reports, the user will be able to filter the report in accordance with various skills of employees (Cost Center, gender, etc.).

I am currently filtering each request separately, for example:

var courses = context.Courses
              .Where(c => c.Employee.CostCenterID == ccID
                     && c.Employee.Rank == rankID
                     ....
                    )
                    .ToList();

The actual filter code is much longer, but it was just a hint. In any case, is there a way to create a common method for filtering the result by an employee? all the objects that I put on this filter method will have a navigation property Employee. I just put IQueryable<entity>or ObjectSet<entity>, and then get filtered IQueryable<entity>or ObjectSet<entity>.

How to do it?

+4
2

:

public Expression<Func<TEntity, bool>> EmployeeFilterDelegateExp<TEntity>( 
    int costCenterId, 
    int rankId )
{
    var parm = Expression.Parameter( typeof( TEntity ), "entity" );
    var employeeProperty = Expression.Property( parm, "Employee" );

    return ( Expression<Func<TEntity, bool>> )Expression.Lambda(
        Expression.AndAlso(
            Expression.Equal( Expression.Property( employeeProperty, "CostCenterID" ), 
                Expression.Constant( costCenterId ) ),
            Expression.Equal( Expression.Property( employeeProperty, "Rank" ), 
                Expression.Constant( rankId ) ) ),
        parm );
}

:

var courses = context.Courses
    .Where( EmployeeFilterDelegateExp<Course>( ccID, rankID ) )
    .ToList();
+2

! , :

public interface IFilterable
{
    Employee Employee
    {
        get;
        set;
    }
}

, Employee, :

public partial class Course: IFilterable
{
}

:

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;
}

, IFilterable:

var list = context.Courses.Filter(sc).ToList();

: SearchCriteria - , .

, , .

+1

Source: https://habr.com/ru/post/1524314/


All Articles