2015-12-03 96 views
1

我试图找到这个答案。LINQ过滤一个数据库列表与另一个数据库列表

我正在使用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.由于使用较少的行,并且是一个简单的解决方案,具有相同的结果。

+0

是第一个引发该异常的查询,还是第二个? –

+0

第二个查询抛出异常。如果有办法做到这一点,我不反对将查询结合起来。 –

+2

尝试从第一个查询中移除.ToList()。 – Harsh

回答

0

它似乎无法使用存储在currentCitizenships中的任何内容创建有效的SQL查询。

获取您需要的国家/地区编号的列表,然后修改您的查询以使用简单的整数集合(或任何CountryId)代替Contains

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

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