Home > Mobile >  How pass multiple filters for a where clause in .NET EF core?
How pass multiple filters for a where clause in .NET EF core?

Time:09-02

As below I am passing a lambda expression to the repository class to filter users based on their ids.

_repository.GetStudentUsers(studentUser => studentUser.StudentId.Equals(srequest.Id));

This is what GetAStudentUsers method in the repository class looks like.

public IQueryable<StudentUser> GetAStudentUsers(Expression<Func<StudentUser, bool>>? filter = null)
        {
            if (filter is not null)
            {
                return dbContext.StudentUsers
                .AsQueryable()
                .AsNoTracking()
                .Where(filter)
                .OrderBy(t => t.StudentName);
            }
            else
            {
                return dbContext.StudentUsers
                    .AsQueryable()
                    .AsNoTracking()
                    .OrderBy(t => t.StudentName);
            }
        }

My problem is how can I modify this to pass multiple filters to the method in the repository class. When I add multiple lambda expressions it is showing cannot use && operator to operands of type bool.

CodePudding user response:

You can call the Where method several times. It builds up the query, effectively ANDing the filters. Until you actually enumerate the IQueryable endpoint, it won't build an actual SQL and query the database.

Like this:

public IQueryable<StudentUser> GetAStudentUsers(params Expression<Func<StudentUser, bool>>[] filters)
{
    // prepare a base query
    var query = dbContext.StudentUsers
            .AsQueryable()
            .AsNoTracking();

    // apply filters
    if (filters != null)
    {
        foreach (var filter in filters) query = query.Where(filter);
    }

    // finalize the query by ordering the results
    return query.OrderBy(t => t.StudentName);
}
  • Related