在linq查询中使用case语句

时间:2013-04-24 11:58:38

标签: linq entity-framework entity-framework-4

我有这样的linq查询:

 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. 在select new {}块中分配时,无法转换值吗?它在项目中给我一个错误。

  2. 我想从数据库中选择ExPAXRate时使用'case',例如我以前编写的SQL:

    CASE ap.SType WHAY'Off Season'THEN at.PerPaxRateOS ELSE at.PerPaxRate END as ExPAXRate

  3. 我可以在linq查询中使用这样的东西吗?

1 个答案:

答案 0 :(得分:2)

  

在select new {}块

中分配时,无法转换值

不,你不能(遗憾地)。 EF不知道如何将其翻译成SQL。

  

我想使用'case'

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

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();
相关问题