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

问题描述 投票:0回答:1

我有一个 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
                        };
sql entity-framework linq
1个回答
1
投票

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
    };
© www.soinside.com 2019 - 2024. All rights reserved.