簡體   English   中英

如何在實體框架提供的Where方法中動態添加“或”條件

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

我有一個 ID 列表,我想從我的產品表(存在於數據庫中)中獲取這些記錄,其中產品 ID 與以下列表中給出的任何 ID 匹配。

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

我知道我可以這樣做 ->

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

但問題是我的列表是動態的。 例如,這里我硬編碼了 3 個值,但它可能是 n 個數字的列表。 所以在那種情況下它會失敗。

所以,我想知道是否有類似的方法或條件 ->

_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);

我在我的項目中使用存儲庫模式,因此我的 GetAll() 方法如下所示:

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

你可以使用.Any()

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

您還可以使用.Contains()替代方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM