在Linq和EF中的联接表上创建条件WHERE子句

本文关键字:创建 条件 子句 WHERE Linq EF | 更新日期: 2023-09-27 17:59:15

要求:

显示此时订单的当前状态。这将返回所有尚未发货的订单以及今天已经发货的订单。

数据结构:

OrderHeader (1) -> (many) ShippingContainerHeaders

下面是我的代码副本。它最初使用oh.CreatedOn部分,现在已被注释掉。但是,该需求变得更为精细,需要考虑那些使用联接表ShippingContainerHeader.ShipDateTimeUTC的特定发货日期的"今日发货"。如果该订单的任何一个船运集装箱都有今天的ShipDateTimeUTC,那么就把它包括在内。但我下面的内容不会编译,并给出了这个错误:

Error 17 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Collections.Generic.IEnumerable<OTIS.Domain.InventoryMgmt.ShippingContainerHeader>' and 'bool'

return orderHeaderRepository
    .SearchFor(oh =>
        oh.FacilityId == intFacilityId
        && oh.OrderType == OrderHeader.OrderTypes.ShipOrder.ToString()
        && (
            oh.StatusId >= (int)OrderHeader.Statuses.Shipped && oh.ShippingContainerHeaders != null
            ? oh.ShippingContainerHeaders.Where(sh => sh.ShipDateTimeUTC >= startDateTime) //(oh.CreatedOn >= startDateTime) && (oh.CreatedOn <= endDateTime)
            : oh.Id > 0
            )
        )

更新

如果我将.Where更改为.Any,我会得到以下错误:

Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[OTIS.Domain.InventoryMgmt.ShippingContainerHeader, OTIS.Domain, Version=1.5.6054.27019, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.

我的解决方案

尽管公认的答案是具体的,因为没有办法实现我试图实现的目标,但它并不能提供替代的解决方案。最后,我只需要创建一个UNION查询,首先查询所有尚未发货的订单,然后为已发货的订单创建另一个查询,并对这两个查询执行并集。

在Linq和EF中的联接表上创建条件WHERE子句

oh.ShippingContainerHeaders != null
            ? oh.ShippingContainerHeaders.Where(sh => sh.ShipDateTimeUTC >= startDateTime) //(oh.CreatedOn >= startDateTime) && (oh.CreatedOn <= endDateTime)
            : oh.Id > 0

这个说法不正确:

oh.ShippingContainerHeaders .Where(sh => sh.ShipDateTimeUTC >= startDateTime) =IEnumerable<ShippingContainerHeader>()

oh.Id > 0是bool!

阅读这里为什么!

无法确定条件表达式的类型,因为"class1"answers"class2"之间没有隐式转换当您希望不同类的对象使用相同的代码时,类之间的转换非常有用。但是,一起工作的两个类不能有相互的和冗余的转换,或者没有隐式转换。class1和class2的类型是独立确定的,并且选择更通用的类型作为条件表达式的类型。有关如何确定类型的详细信息,请参阅Conditional运算符不能隐式转换。若要解析CS0173,请验证类1和类2之间是否存在且仅存在一个隐式转换,无论转换的方向如何,也无论转换的类别如何。有关详细信息,请参阅隐式数值转换表(C#参考)和转换运算符(C#编程指南)。