无法比较'System.Collections.Generic.ICollection`1类型的元素仅支持基本类型,枚举类型和实体类型

Kno*_*uch 36 c# linq entity-framework

我写了这段代码

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();
Run Code Online (Sandbox Code Playgroud)

但是ToList在线上我得到了例外

无法比较'System.Collections.Generic.ICollection`1 [[Project1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]'类型的元素.仅支持基本类型,枚举类型和实体类型.

Nat*_*n A 57

您无法null直接比较相关表格.而是与您的外键成员进行比较(假设使用名为的成员进行PrimaryTable引用).RelatedTableRelatedTableId

sites.Where(s => s.RelatedTableId != null && s.RelatedTable.Any(
    p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
Run Code Online (Sandbox Code Playgroud)

您甚至可以完全删除空检查.由于此查询是针对数据库运行的,因此您无法获得它NullReferenceException,它可能会起作用.你必须仔细检查一下.

  • 我没有得到,RelatedTable是一个列表,怎么会有任何RelatedTableId?我没有这个. (3认同)

Mat*_*att 12

这是因为你在where子句中进行了空检查.

  • 这根本不对。在 where 子句中始终使用空检查。这是对代表包含表的 ICollection 的空检查,这是问题所在...... (3认同)

MiF*_*vil 6

如果导航集合与null进行比较,则可能发生此错误。应该检查是否存在任何记录。在特定示例中,无论如何都使用Any,因此将check collection设置为null是多余的

不正确的

dbContext.MainTable.Where(c => c.RelatedTable==null )
Run Code Online (Sandbox Code Playgroud)

正确

dbContext.MainTable.Where(c => !c.RelatedTable.Any() )
Run Code Online (Sandbox Code Playgroud)


Dan*_*kin 5

集合字段可以为空,在这种情况下你会得到异常NullReferenceException

使用时RelatedTables.Any()

如果你RelatedTables != null在问题中添加 as 那么你可以得到

无法比较“System.Collections.Generic.ICollection`1[[Project1,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]”类型的元素。仅支持基本类型、枚举类型和实体类型。

如果出现NullReferenceException异常,则延迟加载不会关闭,并且您可以很好地对该字段进行延迟加载,然后使用virtual关键字来防止异常标记字段以允许对该字段进行延迟加载

virtual ICollection<Table> RelatedTables{ get; set; }
Run Code Online (Sandbox Code Playgroud)