2015-06-15 19 views
4

我有很多像这样的查询,但我不明白为什么这个错误。当我进行空检查然后使用Contains时,似乎它与我的where子句的某些部分有关。实体框架Linq查询列表 - 使用时出错包含:仅支持基本类型,枚举类型和实体类型

我得到的错误是:

无法比拟的类型元素“System.Collections.Generic.IEnumerable`1 [System.Nullable`1 [System.Int32,mscorlib程序,版本= 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]],mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'。只支持原始类型,枚举类型和实体类型。

以及它抛出代码:

public static IEnumerable<Product> GetProducts(int? productDepartmentId = null, int? productCategoryId = null, IEnumerable<int?> productCategoryIds = null, IEnumerable<string> sections = null) 
{ 
    using (var context = new AppContext()) 
    { 
     var retList = (from obj in context.Products 
         where (productDepartmentId == null || obj.ProductDepartmentId == productDepartmentId) && 
          (productCategoryId == null || obj.ProductCategoryId == productCategoryId) && 
          (productCategoryIds == null || productCategoryIds.Contains(obj.ProductCategoryId)) && 
          (sections == null || sections.Contains(obj.sections)) 
         select obj).ToList(); 
     return retList; 
    } 
} 

这些都是使得它的错误线。我相信,它不会像空校验:

(productCategoryIds == null || productCategoryIds.Contains(obj.productCategoryIds)) && 
(sections == null || sections.Contains(obj.Section)) 

这里是我的方法调用(部分没有被通过):

List<int?> categoryIds = new List<Int?>; 
varList = ProductsDAL.GetProducts(productDepartmentId: productproductDeparmentId, 
            productCategoryId: productCategoryId, 
            productCategoryIds: categoryIds); 

我也试图传递的List键入int。

+0

categoryIds和sections从哪里来? – Hammerstein

+0

他们来自我的代码。它们最终成为逗号分隔的ID列表。我注意到这个问题肯定是由于where子句中有空检查和包含的部分。 –

+0

可能重复[无法比较'System.Collections.Generic.ICollection'类型的元素1只支持原始类型,枚举类型和实体类型](http://stackoverflow.com/questions/23937112/cannot-compare-元素类型 - 系统集合 - generic-icollection1-only-p) –

回答

2

如果它不喜欢空校验,你需要它是可选的,你可以这样做:

List<int> productCategoryIdsTemp = new List<int>(); 
if (productCategoryIds != null) { 
    productCategoryIdsTemp.AddRange(productCategoryIds.Where(id => id != null).Select(id => id.Value)); 
} 
if (sections = null) { 
    sections = new List<string>(); 
} 

,然后在Linq查询使用这样的:

(productCategoryIdsTemp.Count == 0 || productCategoryIdsTemp.Contains(obj.ProductCategoryId)) && 
(sections.Count == 0 || sections.Contains(obj.section)) && 

如果您的productCategoryIds不是可以为null的可为null的整数,您可以像部分一样进行操作。 (真的不明白这是如何被支持的,而不是int列表)

+0

我改变它使用int列表,而仍然得到相同的确切的错误。 –

+1

它不能说完全相同的错误,因为原始错误表示它不能使用IEnumerable的可为空的int。如果你不再使用它,现在必须是一个不同的错误。 – Dacker

+0

我的意思是说,我仍然得到一个错误,说这在最后抱歉:只支持原始类型,枚举类型和实体类型。我不知道该做什么了。因为EF自动生成基于它的产品分类,它可以与我的数据库表的设置方式有任何关系。 productCategoryId是一个可为空的int属性,Section是一个字符串属性。 –

相关问题