Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading