[英]Create conditional WHERE clause on joined table in Linq and EF
需求:
在此時間點顯示訂單的當前狀態。 這將返回所有尚未發貨的訂單以及今天已發貨的那些訂單。
數據結構:
OrderHeader (1) -> (many) ShippingContainerHeaders
下面是我的代碼的副本。 它最初與oh.CreatedOn
部分一起使用,現在已被注釋掉。 但是需求變得更加精細,需要使用聯接表ShippingContainerHeader.ShipDateTimeUTC
的特定發貨日期考慮那些TODAY TODAY。 如果該訂單的任何一個集裝箱的ShipDateTimeUTC
為Today,則將其包括在內。 但是我下面的內容無法編譯並給出此錯誤:
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
更改為.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查詢來首先查詢所有尚未發貨的訂單,再查詢另一個已發貨的訂單,然后對這兩個查詢執行聯合。
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
就是布爾值!
在這里讀為什么!
無法確定條件表達式的類型,因為“類1”和“類2”之間沒有隱式轉換。當您希望不同類的對象使用相同的代碼時,類之間的轉換很有用。 但是,兩個可以一起使用的類不能具有相互和冗余的轉換,也不能具有隱式轉換。 class1和class2的類型是獨立確定的,並且選擇更通用的類型作為條件表達式的類型。 有關如何確定類型的更多信息,請參見條件運算符不能隱式轉換。 要解析CS0173,請驗證class1和class2之間是否存在一個且只有一個隱式轉換,而不管該轉換在哪個方向上以及該轉換在哪個類中進行。有關更多信息,請參見隱式數值轉換表(C#參考)和轉換運算符(C#編程指南)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.