簡體   English   中英

在 where 子句中設置了動態值的實體框架不起作用

[英]Entity Framework with dynamic value set in where clause not working

我的數據庫和相應的 class 結構如下

Class Helper:
   List<Util> UtilityInfo,
   
Class Util :
   int Id

我有以下值的過濾器數組

int[] idArray = { 1, 2, 3};

預期的查詢格式:

 _dbContent.Helper.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id = 1 || ut => ut.Util.id == 2 || ut => ut.Util.id == 3));

我想通過在 id 的數組上循環來實現相同的目的。

當我執行上面的查詢時,它工作正常,但想使用循環動態構造相同的。

我嘗試使用以下模式,但它在[ut.Util.id == item]添加了一些 class 級別的表達式,在 Visual Studio 中觀察到相同的調試表達式內容。

最后因為在檢索數據時出現錯誤。

var helperInfo = new List<Helper>()

foreach(var item in idArray)
{
    helperInfo = helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item));
}

注意:我已經成功完成了下面的模式,但希望通過循環實現相同的目標

helper= helper.Where
(
  hp => idArray.Any
  (
     uId => hp.utilityInfo!= null &&
     v.utilityInfo.Any
     (
        ut => ut.User != null &&
        ut.Id == uId
     )
  )).ToList();
}

更新 2

您可以在下面的 prev 更新中通過相同的概念迭代IQueryable或使用表達式

var helperInfo = _dbContent.Helper;
var filteredHelperInfo = new List<Helper>();

foreach(var item in idArray)
{
   filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)).ToList());
}

如果我現在很好理解,如果您需要使用循環查詢幫助列表,您需要創建新列表並在每次迭代中添加過濾項目,如下所示

注意:在您的第一次迭代中的代碼中,您的列表將在第二次使用第一個 id 進行過濾時,您不會在第二個 id 的列表中找到任何項目,因此您的列表將為空

var helperInfo = new List<Helper>();
var filteredHelperInfo = new List<Helper>();

foreach(var item in idArray)
{
   filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)));
}

更新

如果我現在很好理解,如果您需要使用循環查詢幫助列表,您需要創建新列表並在每次迭代中添加過濾項目,如下所示

注意:在您的第一次迭代中的代碼中,您的列表將在第二次使用第一個 id 進行過濾時,您不會在第二個 id 的列表中找到任何項目,因此您的列表將為空

var helperInfo = new List<Helper>();
var filteredHelperInfo = new List<Helper>();

foreach(var item in idArray)
{
   filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)));
}

最少代碼的舊答案

您可以使用 contains 而不是像下面那樣循環,這將獲得您提到的數組中具有相同 id 的所有項目

helperInfo = helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && idArray.Contains( ut.Util.id)));

你可以用這個

int[] idarray = { 1, 3, 5 };
var list = context.Helpers.Include(x => x.Utilities.Where(y => idarray.Contains(y.Id))).ToList();

結果

在此處輸入圖像描述

暫無
暫無

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

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