Home > Back-end >  The name "covid" doesn't exist in the current context
The name "covid" doesn't exist in the current context

Time:12-26

Hi i convert sql query to linq i got this error. when i remove group by there isn't exception but i should use group by. why i got this exception ?

public List<BiontechSinovacCovidDto> GetBiontechSinovacCovidDto()
{
    using(SirketDBContext context=new SirketDBContext())
    {
        var result = 
            from asi in context.Asilar
            join covid in context.Covids
                on asi.CovidId equals covid.CovidId
            group asi by asi.AsiIsmi into isim
            select new BiontechSinovacCovidDto
            {
                AsiIsmi=isim.Key,
    //exception    OrtalamaCovidSuresi=(EF.Functions.DateDiffDay(covid.CovidYakalanmaTarih, covid.CovidBitisTarih)).Average()
            };
        return result.ToList();                                              
    }
}

my sql query

Select 
    AsiIsmi,
    AVG(Cast(DATEDIFF(Day,CovidYakalanmaTarih, CovidBitisTarih)AS FLOAT)) as OrtalamaCovidSuresi 
From Asilar 
    INNER JOIN Covids on Covids.CovidId=Asilar.CovidId 
group by AsiIsmi
|AsiIsmi| OrtalamaCovidSuresi|
-------  ------------------
Biontech      13.6667
Sinovac        15

BiontechSinovacCovidDto

public class BiontechSinovacCovidDto
{
    public string AsiIsmi { get; set; }
    public double OrtalamaCovidSuresi { get; set; }
}

CodePudding user response:

Average has overload which accepts lambda. You have to use this version. Also you have to group covid in this case.

public List<BiontechSinovacCovidDto> GetBiontechSinovacCovidDto()
{
    using (var context = new SirketDBContext())
    {
        var result = 
            from asi in context.Asilar
            join covid in context.Covids
                on asi.CovidId equals covid.CovidId
            group covid by asi.AsiIsmi into isim
            select new BiontechSinovacCovidDto
            {
                AsiIsmi = isim.Key,
                OrtalamaCovidSuresi = isim.Average(x => EF.Functions.DateDiffDay(x.CovidYakalanmaTarih, x.CovidBitisTarih))
            };

        return result.ToList();                                              
    }
}
  • Related