我有一个 SQL 查询,我想将其转换为 linq

I have a SQL query and I want to convert it to linq

我有一个 SQL 查询,我想将其转换为 Linq。

这是我的 SQL 查询:

SELECT
    Calisanlar.CalisanId,
    CovidYakalanmaTarih, 
    CovidBitisTarih 
FROM
    Calisanlar 
INNER JOIN 
    Covids ON Calisanlar.CalisanId = Covids.CalisanId 
WHERE
    Calisanlar.CalisanId IN (SELECT TOP 10 CalisanId  
                             FROM Hastaliklar 
                             GROUP BY CalisanId 
                             ORDER BY COUNT(*) DESC)
    AND DATEDIFF(DAY, CovidYakalanmaTarih, GETDATE()) BETWEEN 0 AND 30 

我写了这段 C# 代码,但它没有按预期工作,因为我没有写“DATEDIFF(DAY, CovidYakalanmaTarih, GETDATE()) BETWEEN 0 AND 30” linq 版本:

var query = context.Hastaliklar
                   .GroupBy(x => x.CalisanId)
                   .OrderByDescending(grp => grp.Count())
                   .Select(grp => grp.Key)
                   .Take(10)
                   .ToList();

var result = from hastalik in context.Hastaliklar
             join covid in context.Covids
                  on hastalik.CalisanId equals covid.CalisanId
             where query.Contains(hastalik.CalisanId) 
                   && EF.Functions.DateDiffDay(covid.CovidYakalanmaTarih, covid.CovidBitisTarih)
             select new SonBirAyCovidDto
                        {
                            CalisanId = covid.CalisanId,
                            CovidYakalanmaTarih = covid.CovidYakalanmaTarih,
                            CovidBitisTarih = covid.CovidBitisTarih
                        };

在 EF Core 中没有直接转换为 BETWEEN,但您可以创建其他条件。此外,最好从第一个查询中删除 ToList(),在这种情况下,您将只有一次往返数据库。

var query = context.Hastaliklar
    .GroupBy(x => x.CalisanId)
    .OrderByDescending(grp => grp.Count())
    .Select(grp => grp.Key)
    .Take(10);

var result = 
    from hastalik in context.Hastaliklar
    join covid in context.Covids
        on hastalik.CalisanId equals covid.CalisanId
    where query.Contains(hastalik.CalisanId) 
        && covid.CovidYakalanmaTarih <= covid.CovidBitisTarih
        && EF.Functions.DateDiffDay(covid.CovidYakalanmaTarih, covid.CovidBitisTarih) <= 30
    select new SonBirAyCovidDto
    {
        CalisanId = covid.CalisanId,
        CovidYakalanmaTarih = covid.CovidYakalanmaTarih,
        CovidBitisTarih = covid.CovidBitisTarih
    };