簡體   English   中英

在 EF Core 3.1 的 Where () 中使用 Any()

[英]Using Any() inside Where () in EF Core 3.1

await this.dbContext
          .UserTeams
          .Where(ut =>
                   teamMembers.Any(tm => tm.UserId == ut.UserId 
                                         && ut.TeamId == tm.TeamId))
          .ToListAsync();

這里的 teamMember 是一個簡單的列表,其中包含分組UserIdsTeamIds 如果我使用Contains()UserIdTeamId是此處的復合鍵,則此方法有效。

這是一個相當簡單的查詢,無法翻譯。

錯誤:

System.InvalidOperationException: The LINQ expression 'DbSet<UserTeam>
     .Where(u => __teamMembers_0
         .Any(tm => u.TeamId == tm.TeamId && u.UserId == tm.UserId))' 
could not be translated. 
Either rewrite the query in a form that can
be translated, or switch to client evaluation explicitly by inserting
a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
ToListAsync()

問題是 EF 不能翻譯復雜的對象。 EF can only translate .NET memory object in SQL parameters, and use those SQL parameters in the SQL query.

我看到一個可能有效的選項。 由於除了使用組合值進行簡單查找之外,您沒有做任何特定的事情,您可以嘗試在單個 SQL 參數中轉換用戶 ID/團隊 ID 組合。 例如,值為“-”的字符串。 我假設你的 id 是簡單的整數。 如果它們是字符串,則可能需要使用不同的分隔符。 使用該組合值在您的數據庫源中查找任何匹配項。

下面的代碼未經測試,可能無法正常工作。 另一種方法是創建某種視圖以在數據庫端創建組合值。

    var memberIds = teamMembers.Select(tm => $"{tm.UserId}-{tm.TeamId}").ToArray();
    await this.dbContext
              .UserTeams
              .Where(ut => memberIds.Contains(
                               SqlFunctions.StringConvert((double?)tm.UserId) + "-" +
                               SqlFunctions.StringConvert((double?)tm.TeamId)
                           )
                    )
              .ToListAsync();

暫無
暫無

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

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