问题描述
我写了这个代码
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行我得到异常
However at the ToList line I am getting the exception
{不能比较类型的元素'System.Collections.Generic.ICollection`1 [PROJECT1,版本= 1.0.0.0,文化=中立,公钥=空]]'。只有基本类型,枚举类型和实体类型都支持。}
{"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."}
推荐答案
您不能将相关的表比较空
直接。相反,比较对你的外键成员(假设 PrimaryTable
参考 RelatedTable
使用名为成员 。s.RelatedTableId = NULL&安培;!&放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只有基本类型,枚举类型和实体类型的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!