【问题标题】:Cannot implicitly convert type System.Collections.Generic.IEnumerable<> to bool无法将类型 System.Collections.Generic.IEnumerable<> 隐式转换为 bool
【发布时间】:2013-01-31 22:05:14
【问题描述】:

我正在开发一个 ASP.NET MVC 4 应用程序,并尝试在 Entity Framework 5 中运行这个 Lambda 表达式。

var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
            .Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
            .Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
            .Where(d => d.GNL_CustomerLaptopProduct.Where(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));

我收到此错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable&lt;ITKaranDomain.GNL_CustomerLaptopProduct&gt;' to 'bool'

我知道最后一个 where 子句是错误的,但我不知道如何更正它。

【问题讨论】:

  • 正如 Andrew 在他的回答中指出的那样,您需要使用 Any 作为 Where will return an IEnumerable` 并且 Any 的谓词需要一个 bool 返回函数。

标签: c# entity-framework


【解决方案1】:

您可能希望在末尾的.Any 子句中使用另一个.Any 而不是.Where

var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
            .Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
            .Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
            .Any(d => d.GNL_CustomerLaptopProduct.Any(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));

【讨论】:

    【解决方案2】:

    在最后一个语句中使用Where ( Any ) 来选择至少有一种产品满足您的条件的客户:

    var customer = db.GNL_Customer
       .Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
       .Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
       .Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
       .Where(d => brandID == null || d.GNL_CustomerLaptopProduct.Any(r => r.BrandName == brandID));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多