将SQL查询转换为LINQ

时间:2017-11-23 10:38:42

标签: c# sql linq

我想如果有人帮我将这个SQL查询转换为LINQ语法。

SELECT i.Id, i.Condomino as Condomino, i.Interno as Interno, 
    p.NomePiano as NomePiano, s.Nome as NomeCondominio,
    m.millesimi_fabbisogno_acs, m.millesimi_fabbisogno_riscaldamento
    FROM Interni i
    INNER JOIN Piani p ON i.IdPiano = p.Id
    INNER JOIN Stabili s ON i.IdStabile = s.Id
    LEFT JOIN MillesimiTabellaC m ON i.Id = m.idInterno
    WHERE s.IdCondominio = {0}

我尝试使用这样的东西,但是没有用......

return _Db.Interni.Include("Piani").Where(x => x.Piani.IdCondominio == iidcond).ToList();

1 个答案:

答案 0 :(得分:2)

我是在现场制作的(所以它没有经过测试),但也许它足以让你知道。我还假设你的数据库模型设置了外键。

var result = _db.Interni
                .Where(i => i.Stabili.IdCondominio = [value])
                .Select(i => new
                             {
                                 i.Id,
                                 Condomino = i.Condomino, 
                                 Interno = i.Interno,
                                 NomePiano = i.Piani.NomePiano,
                                 NomeCondominio = i.Stabili.Nome,
                                 i.MillesimiTabellaC.millesimi_fabbisogno_acs, 
                                 i.MillesimiTabellaC.millesimi_fabbisogno_riscaldamento
                             })
                .ToList();

<强>更新

如果您在InterniMillesimiTabellaC之间没有外键,请尝试以下操作:

var result = _db.Interni
                .Include(i => i.Piani)
                .Include(i => i.Stabili)
                .Where(i => i.Stabili.IdCondominio = [value])
                .Select(i => new
                             {
                                Interni = i,
                                MillesimiTabellaC = _db.MillesimiTabellaC.Where(m => i.Id = m.idInterno)
                             })
                .Select(x => new
                             {
                                 Id = x.Interni.Id,
                                 Condomino = x.Interni.Condomino, 
                                 Interno = x.Interni.Interno,
                                 NomePiano = x.Interni.Piani.NomePiano,
                                 NomeCondominio = x.Interni.Stabili.Nome,
                                 x.MillesimiTabellaC?.millesimi_fabbisogno_acs, 
                                 x.MillesimiTabellaC?.millesimi_fabbisogno_riscaldamento
                             })
                .ToList();