linq连接表与select子查询?

时间:2016-10-24 14:51:48

标签: c# sql asp.net sql-server linq

SQL查询,如下所示,我试图使它成为LinQ ,,但它不能正常工作,但linq不工作......我的错误在哪里?

select (select X from X where X.yid=Y.id and X.FormNo=4),* 
from Y 
where Y.servicetype=3

这个SQL查询正在运行

public IEnumerable<NBelge> BelgeleriGetir2(int servicetype, int formno)
{
    var db = new SERVISBAKIMEntities();
    var result = (from g in db.Y
                  join d in db.X
                  on g.id equals d.yid into ps
                  from d in ps.DefaultIfEmpty()
                  where g.servicetype == servicetype && d.FormNo == formno
                  select new {});
}

这样的linq代码却无法正常工作?哪里是真的?

1 个答案:

答案 0 :(得分:0)

使用子查询最直接的是:

var result = (from y in db.Y
              where y.servicetype == 3
              select new { y, x = (from x in db.X 
                                   where x.yid == y.id && x.FormNo == 4 
                                   select x.x).FirstOrDefault() }
             ).ToList();

但我认为使用join更具可读性。在sql中它将如下所示:

select X.x, Y.*
from Y
join X on Y.id == X.yid
where Y.servicetype == 3
and X.FormNo == 4

使用linq:

var result = (from y in db.Y
              where y.servicetype == 3
              join x in db.X on y.id equals x.yid
              where x.FormNo == 4
              select new { y, x }).ToList();