Using case statement in linq query

2019-04-13 03:42发布

问题:

I have a linq query like this :

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

I have two questions:

  1. Can't I convert value while assigning in the select new {} block ? it is giving me an error in project.

  2. I want use 'case' while selecting ExPAXRate from the database for example in SQL I used to write :

    CASE ap.SType WHEN 'Off Season' THEN at.PerPaxRateOS ELSE at.PerPaxRate END AS ExPAXRate

Can I use something like this in linq query ?

回答1:

Can't I convert value while assigning in the select new {} block

No, you can't (sadly). EF doesn't know how to translate it into SQL.

I want use 'case'

You can use the ternary operator (?):

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

(assuming that at.OffSeason exists).

A solution for the conversion issue could be to project into an anonymous type first and then, in memory, to 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();