Search code examples
c#asp.net-coreentity-framework-corewhere-clauseunit-of-work

How to dynamically add "OR" conditions in Where method provided by Entity Framework


I have a list of Ids and I want to fetch those records from my Products table (present in database) where Product Id matches to any Ids given in the following list.

List<int> ids = new List<int> { 1, 2, 3 };

I know I can do like this ->

_unitOfWork.Product.GetAll(p => p.Id == 1 || p.Id == 2 || p.Id == 3);

But problem with this is my list is dynamic. Here just for example I hard coded 3 values but it could be the list of n numbers. So in that case it will fail.

So, I want to know if there a way to or condition like ->

_unitOfWork.Product.GetAll(p => p.Id == //all ids present in list with OR conditions, something like foreach loop which will iterate through my list of ids & internally will make condition like I made above with hard coded values);

I am using repository pattern in my project, hence my GetAll() method looks like this:

public IEnumerable<T> GetAll(Expression<Func<T, bool>>? filter = null, string? includeProperties = null)
{
    IQueryable<T> query = dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (includeProperties != null)
    {
        query = IncludeProperties(query,includeProperties);
    }

    return query.ToList();
}

Solution

  • You can use .Any(),

    List<int> ids = new List<int> { 1, 2, 3 };
    _unitOfWork.Product.GetAll(p => ids.Any(x => x == p.Id));
    

    Alternate way you can also use .Contains()

    _unitOfWork.Product.GetAll(p => ids.Contains(p.Id));