【问题标题】:How to dynamically add "OR" conditions in Where method provided by Entity FrameworkEntity Framework提供的Where方法中如何动态添加“OR”条件
【发布时间】:2023-01-17 00:08:39
【问题描述】:

我有一个 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() 方法如下所示:

enter image description here

【问题讨论】:

    标签: c# asp.net-core entity-framework-core where-clause unit-of-work


    【解决方案1】:

    你可以使用.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));
    

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多