如何在LINQ中重写或使用EF对象查询?
select r.UserName,
(select count(*) from tbl1 where UserName = r.UserName) as tbl1Count,
(select max(CreatedDate) from tbl2 where UserName = r.UserName) as tbl2Date,
(select max(SomeDate) from tbl3 where UserName = r.UserName) as tbl3Date,
max(r.DateRegistered) as SomeDate
from sometable r
group by r.UserName
答案 0 :(得分:1)
尝试此查询
var objlist = (
From a in Contex.UserName
From b in Contex.tbl1.where(x=>x.UserName==a.UserName).DefaultEmpty()
From c in Contex.tbl2.where(x=>x.UserName==a.UserName).DefaultEmpty()
From d in Contex.tbl3.where(x=>x.UserName==a.UserName).DefaultEmpty()
group a by a.UserName into pg
Select new {
UserName = pg.UserName,tbl1count=pg.Count(x=>x.tbl1id)
,tbl2Date = pg.max(x=>x.CreatedDate)
,tbl3Date = pg.max(x=>x.SomeDate)
,SomeDate = pg.max(x=>x.DteRegistered)
}).ToList();
答案 1 :(得分:1)
请尝试以下代码
StackOverflowEntities db = new StackOverflowEntities();
var result = (from p in db.SomeTables
join q in db.Table_1 on p.UserName equals q.UserName into Q
from q in Q.DefaultIfEmpty()
join r in db.Table_2 on p.UserName equals r.UserName into R
from r in R.DefaultIfEmpty()
join s in db.Table_3 on p.UserName equals s.UserName into S
from s in R.DefaultIfEmpty()
group new { p, q, r, s } by p.UserName into g
select new
{
UserName = g.Key,
tbl1Count = g.Count(w => w.q != null),
tbl2Date = g.Max(w => w.r.CreatedDate),
tbl3Date = g.Max(w => w.s.SomeDate),
SomeDate = g.Max(w => w.p.DateRegistered)
}).ToList();