简体   繁体   中英

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.

You can call the Where method several times. It builds up the query, effectively AND ing 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM