【问题标题】:Convert SQL resquest to C# lambda Expression将 SQL 请求转换为 C# lambda 表达式
【发布时间】:2017-07-27 10:00:48
【问题描述】:

我正在尝试将 sql 请求转换为 lambda 表达式,但我只知道如何使用 where 语句来完成。这是我的要求:

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

并且@UtilisateurId 将是从视图中的 DropDownList 中选择的值。

在我的控制器中,我有这个代码:

  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 中选择的值。 谢谢

【问题讨论】:

标签: c# sql list lambda expression


【解决方案1】:

试试这个。我发现使用 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();

【讨论】:

  • 我对这种语法的理解要好得多。感谢您的帮助。
  • 卡米尔没问题
【解决方案2】:

这是你想要的吗,

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);

}

【讨论】:

    【解决方案3】:

    由于您的导航属性仍然​​未知,这或多或少是一个疯狂的猜测...

    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);
    
        }
    

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多