2017-07-27 59 views
1

我想將一個sql請求轉換爲lambda表達式,但我只知道如何使用where語句來完成此操作。這是我的要求:將SQL resquest轉換爲C#lambda表達式

SELECT  Projet.ProjetId, Projet.Libelle, UtilisateurInProjet.UtilisateurId 
FROM   Projet INNER JOIN 
         UtilisateurInProjet ON Projet.ProjetId = UtilisateurInProjet.ProjetId 
WHERE  (UtilisateurInProjet.UtilisateurId = @UtilisateurId) 

和@UtilisateurId將成爲視圖中DropDownList的選定值。

以我控制器,I有這樣的代碼:

public JsonResult GetProjsName(int id) 
    { 
     db.Configuration.ProxyCreationEnabled = false; 
     List<Projet> liprojs = db.Projets.Where(x => x.ProjetId == id).ToList(); 
     return Json(liprojs, JsonRequestBehavior.AllowGet); 

    } 

和 「id」 爲從在視圖中的DropDownList選定的值。 謝謝

+0

你的代碼看起來像你正在使用EntityFramework ...是你的ORM? – DarkSquirrel42

+1

請參閱msdn:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b – jdweng

+0

[C#連接/ Linq和Lambda位置]的可能重複(https://stackoverflow.com/questions/2767709/ c-sharp-joins-where-with-linq-and-lambda) – Serg

回答

0

試試這個。我發現爲連接使用Linq查詢語法比使用Linq擴展更容易。

var liprojs = (from p in db.Projets 
       join uip in db.UtilisateurInProjet on p.ProjetID equals uip.ProjetID 
       where uip.UtilisateurId == utilisateurId 
       select new {p.ProjetId, p.Libelle, uip.UtilisateurId}).ToList(); 
+0

我明白這個語法好得多。感謝您的幫助。 – Kamil

+0

沒問題卡米爾 –

0

這是你想要的,

public JsonResult GetProjsName(int id) 
{ 
    db.Configuration.ProxyCreationEnabled = false; 
    List<Projet> liprojs = db.Projets.Join(db.UtilisateurInProjet,projet=> projet.ProjetId,utilisateurInProjet => utilisateurInProjet.ProjetId,(projet,utilisateurInProjet) => new {projet.ProjetId, projet.Libelle, utilisateurInProjet.UtilisateurId}).Where(utilisateurInProjet.UtilisateurId==id).ToList(); 
    return Json(liprojs, JsonRequestBehavior.AllowGet); 

} 
0

因爲您的導航性能仍然是未知的,這是或多或少胡亂猜測......

public JsonResult SomeMethod(int id) 
    { 
     db.Configuration.ProxyCreationEnabled = false; 
     return Json(db.UtilisateurInProjet.Where(x=>x.id==id).SelectMany(x=>x.Projects.Select(p=>new { ProjetId=p.ProjetId, Libelle=p.Libelle, UtilisateurInProjet=x.UtilisateurId})).ToList(), JsonRequestBehavior.AllowGet); 

    }