无法比较类型“System.Collections.Generic.ICollection”的元素1只支持基本类型,枚举类型和实体类型 [英] Cannot compare elements of type 'System.Collections.Generic.ICollection`1 Only primitive types, enumeration types and entity types are supported
问题描述
我写了这段代码
IQueryable<Site> sites = context.MainTable.Include("RelatedTable");
if (!string.IsNullOrEmpty(param1)) {
sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
}
foreach (string secondaryPolicy in secondaryPolicies)
{
sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == secondaryPolicy.ToLower() && p.PolicyType == "secondary"));
}
return sites.ToList();
然而在 ToList
例外
无法比较类型为
'System.Collections.Generic.ICollection`1的元素[[Project1,Version = 1.0 .0.0,
Culture = neutral,PublicKeyToken = null]]'。只支持基本类型
枚举类型和实体类型。
Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.
推荐答案
你无法直接将相关表与 null
进行比较。相反,与您的外键成员进行比较(假设 PrimaryTable
参考 RelatedTable
使用一个名为 RelatedTableId
。
You can't compare a related table to null
directly. Instead, compare against your foreign key member (assuming that PrimaryTable
reference RelatedTable
using a member called RelatedTableId
.
sites.Where(s => s.RelatedTableId != null && s.RelatedTable.Any(
p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
甚至可以完全删除空检查,因为这个查询是针对数据库运行的,所以你不会得到一个 NullReferenceException
它可能会工作,你必须仔细检查,虽然。
You may even be able to get away with removing the null check completely. Since this query is run against the database, you won't get a NullReferenceException
and it may work. You'll have to double check on that though.
这篇关于无法比较类型“System.Collections.Generic.ICollection”的元素1只支持基本类型,枚举类型和实体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!