2013-04-24 142 views
2

我有一個LINQ查詢是這樣的:使用case語句

var trfplanList = (from at in entities.tdp_ProviderAccomodationType 
         join ap in entities.tdp_ProviderAccomodationTariffPlan on at.PATID equals ap.FK_PATID 
         join ac in entities.tdp_ProviderAccomodationCategory on ap.FK_PACID equals ac.PACID 
         where at.FK_ProviderID == CityID && at.IsApproved == 0 && ap.IsApproved == 0 && ac.AccomodationCategory == "Double Occupy" 
         orderby at.AccomodationType,ap.FromDate,ap.SType 
         select new AccomodationTariff 
         { 
          AccomodationType = at.AccomodationType, 
          SType = ap.SType, 
          FromDate = Convert.ToDateTime(ap.FromDate), 
          ToDate = Convert.ToDateTime(ap.ToDate), 
          RoomTariff = Convert.ToDecimal(ap.Rate), 
          ExPAXRate = Convert.ToDecimal(at.PerPaxRate) 
         }).ToList(); 

我有兩個問題:

  1. 我不能轉換值,而在選擇新的分配{}塊?它在項目中給我一個錯誤。

  2. 我希望在從數據庫例如SQL選擇ExPAXRate使用 '案例' 我以前寫:

    CASE ap.SType如果 '淡季',那麼at.PerPaxRateOS ELSE at.PerPaxRate END AS ExPAXRate

我可以在linq查詢中使用這樣的東西嗎?

回答

2

我不能轉換值,而在選擇新的分配{}塊

不,你不能(黯然)。 EF不知道如何將其轉換爲SQL。

我想用 '情況'

您可以使用三元運算(?):

ExPAXRate = at.OffSeason ? at.PerPaxRateOS : at.PerPaxRate 

(假設at.OffSeason存在)。

一種轉換的問題解決方案可能是投射到一個匿名類型第一,然後在內存中,以AccomodationTariff

... 
select new 
{ 
    AccomodationType = at.AccomodationType, 
    SType = ap.SType, 
    FromDate = ap.FromDate, 
    ToDate = ap.ToDate, 
    RoomTariff = ap.Rate, 
    ExPAXRate = at.PerPaxRate 
}).AsEnumerable() 
.Select(x => new AccomodationTariff 
{ 
    AccomodationType = x.AccomodationType, 
    SType = x.SType, 
    FromDate = Convert.ToDateTime(x.FromDate), 
    ToDate = Convert.ToDateTime(x.ToDate), 
    RoomTariff = Convert.ToDecimal(x.Rate), 
    ExPAXRate = Convert.ToDecimal(x.PerPaxRate) 
}).ToList(); 
+0

ExPAXRate = at.OffSeason? at.PerPaxRateOS:at.PerPaxRate,這裏我想檢查一下這樣的ExPAXRate = ap.SType ==「Off Season」? at.PerPaxRateOS:at.PerPaxRate,但它給了我一個錯誤 – DharaPPatel 2013-04-25 04:30:01

+0

okey我得到的解決方案,我應該寫:ExPAXRate =(ap.SType ==「Off Season」)? at.PerPaxRateOS:at.PerPaxRate – DharaPPatel 2013-04-25 05:53:14