簡體   English   中英

實體框架Linq查詢到列表 - 使用包含時出錯:僅支持基本類型,枚舉類型和實體類型

[英]Entity Framework Linq Query to List - Error when using contains: Only primitive types, enumeration types and entity types are supported

我有很多像這樣的查詢,但我無法弄清楚為什么這個錯誤。 當我進行null檢查然后使用Contains時,似乎它與我的where子句的部分有關。

我得到的錯誤是:

無法比較'System.Collections.Generic.IEnumerable`1 [[System.Nullable`1 [[System.Int32,mscorlib,Version = 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;
    }
}

這些是導致錯誤的行。 我相信它不喜歡null檢查:

(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);

我也試過傳入一個int類型的List。

如果它不喜歡null檢查並且你需要它是可選的,你可以這樣做:

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不是IEnumerable可以為null的int,你可以對section進行相同的操作。 (不要真正理解如何支持它而不是int列表)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM