Mat*_*son 7 .net c# linq entity-framework
我有很多像这样的查询,但我无法弄清楚为什么这个错误.当我进行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;
}
}
Run Code Online (Sandbox Code Playgroud)
这些是导致错误的行.我相信它不喜欢null检查:
(productCategoryIds == null || productCategoryIds.Contains(obj.productCategoryIds)) &&
(sections == null || sections.Contains(obj.Section))
Run Code Online (Sandbox Code Playgroud)
这是我对方法的调用(部分未被传递):
List<int?> categoryIds = new List<Int?>;
varList = ProductsDAL.GetProducts(productDepartmentId: productproductDeparmentId,
productCategoryId: productCategoryId,
productCategoryIds: categoryIds);
Run Code Online (Sandbox Code Playgroud)
我也试过传入一个int类型的List.
如果它不喜欢空检查并且您需要它是可选的,您可以这样做:
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>();
}
Run Code Online (Sandbox Code Playgroud)
然后在您的 Linq 查询中使用:
(productCategoryIdsTemp.Count == 0 || productCategoryIdsTemp.Contains(obj.ProductCategoryId)) &&
(sections.Count == 0 || sections.Contains(obj.section)) &&
Run Code Online (Sandbox Code Playgroud)
如果您的productCategoryIds 不是可空整数的IEnumerable,您可以执行与部分相同的操作。(不太明白这需要如何支持而不是 int 列表)