如何将我的SQL命令转换为linq命令?

时间:2014-01-23 10:59:03

标签: sql sql-server linq

我想将此续集指令转换为Linq指令。 数据库上下文名为contestoDB

这是我的SQL查询:

SELECT 
   DATEDIFF(DD, GETDATE(), CERTIFICATI_2.DATA_SCADENZA) AS DAYSTOGO, 
   CERTIFICATI_2.DATA_SCADENZA, AREE.NOME_AREA, 
   AGENTS.MACCHINA, AGENTS.ALIAS_AGENT, NUMBEFOR_ALERTDAYS, 
   AGENTS.USER_ABILIATI, UTENTI_2.UTENTE as RESPONSABILE, UTENTI_2.EMAIL 
FROM  
   CERTIFICATI_2 
INNER JOIN 
   AGENTS ON CERTIFICATI_2.ID_AGENTS = AGENTS.ID_AGENT 
INNER JOIN 
   UTENTI_2 ON AGENTS.RESPONSABILE = UTENTI_2.ID 
INNER JOIN 
   AREE ON AGENTS.ID_AREA = AREE.ID_AREA
WHERE 
   DATEDIFF(DD,GETDATE(),CERTIFICATI_2.DATA_SCADENZA) = ISNULL( NUMBEFOR_ALERTDAYS,57)
    OR DATEDIFF(DD,GETDATE(),CERTIFICATI_2.DATA_SCADENZA) = 0  
ORDER BY 
    CERTIFICATI_2.DATA_SCADENZA

是否有人帮我转换Linq?

谢谢!

PS:我已经尝试过Linquer,但它没有转换我的sql,因为ISNULLDATEDIFF会在转换中产生问题并关闭程序。

1 个答案:

答案 0 :(得分:0)

这应该有效:

var query = from cert in db.Certificati
            join agent in db.Agents
            on cert.Id_Agents equals agent.Id_Agent
            join utenti in db.Utenti
            on agent.Responsabile equals utenti.ID
            join aree in db.Aree
            on agent.Id_Area equals aree.Id_Area
            where (DateTime.Now - cert.Data_Scadenza).TotalDays == 0 
               || (DateTime.Now - cert.Data_Scadenza).TotalDays == cert.NUMBEFOR_ALERTDAYS ?? 57
            orderby cert.Data_Scadenza descending
            select new 
            {
                DaysToGo = (DateTime.Now - cert.Data_Scadenza).TotalDays,
                // other columns
            };