2017-07-27 45 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); 

    }