【问题标题】:Using case statement in linq query在 linq 查询中使用 case 语句
【发布时间】:2013-04-24 20:11:55
【问题描述】:

我有一个这样的 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 WHEN 'Off Season' THEN at.PerPaxRateOS ELSE at.PerPaxRate END AS ExPAXRate

我可以在 linq 查询中使用类似的东西吗?

【问题讨论】:

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


    【解决方案1】:

    在 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();
    

    【讨论】:

    • ExPAXRate = at.OffSeason ? at.PerPaxRateOS : at.PerPaxRate ,在这里我想检查类似 ExPAXRate = ap.SType == "Off Season" 的内容? at.PerPaxRateOS : at.PerPaxRate ,但它给了我一个错误
    • 好吧,我得到了解决方案,我应该写: ExPAXRate = (ap.SType == "Off Season") ? at.PerPaxRateOS : at.PerPaxRate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2015-05-06
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多