簡體   English   中英

LINQ用另一個數據庫列表過濾數據庫列表

[英]LINQ filter a database list with another database list

我試圖找到答案。

我正在使用LINQ,並嘗試用另一個列表過濾數據庫列表,以從成員已經是公民的國家列表中刪除國家。

var currentCitizenships = DbContext.Citizenships
            .Where(c => c.MemberId == CurrentUser.MemberId)
            .Include(c => c.Country)
            .ToList();

var filtered = DbContext.Countries
            .Where(c => !currentCitizenships.Any(current => current.Country.CountryId == c.CountryId));

我收到Not supported exception並顯示以下消息:

Unable to create a constant value of type 'Project.EntityFramework.Models.Citizenship'. Only primitive types or enumeration types are supported in this context.

兩種解決方案

  1. 刪除第一個查詢的ToList()。

  2. 所選答案。

我選擇1.是因為使用了更少的行,並且是具有相同結果的更簡單的解決方案。

似乎它無法使用currentCitizenships存儲的內容創建有效的SQL查詢。

首先獲取您需要的國家/地區ID列表,然后修改查詢以在簡單的整數集合(或任何CountryId )上使用Contains

var countryIds = currentCitizenships.Select(x => x.Country.CountryId).ToList();

var filtered = DbContext.Countries.Where(c => !countryIds.Contains(c.CountryId));

暫無
暫無

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

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