如何在LINQ中实现外部应用?我有点问题。
这是我正在使用的SQL查询。
SELECT u.masterID
,u.user
,h.created
FROM dbo.Users u
OUTER APPLY (SELECT TOP 1 * FROM UserHistory h where h.masterID = u.masterID ORDER BY created DESC) h
答案 0 :(得分:16)
from u in Users
join UserHistory on u.masterID equals h.masterID into h
select new {
u.masterID,
u.user,
Created = h.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault()
}
或者,与协会:
from u in Users
let created = u.UserHistories.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault()
select new
{
u.masterID,
u.user,
Created = created
}
答案 1 :(得分:7)
from u in Users
join UserHistory on u.masterID equals h.masterID into h
select new {u.masterID, u.user, h.created.OrderByDescending().First()}
答案 2 :(得分:0)
外部应用产生左外连接的结果,
查询应该是:
var q =
from u in db.Users
join h in db.UserHistory on u.masterID equals h.masterID into ps
from p in ps.DefaultIfEmpty()
select new {
masterID = u.masterID
,user = u.user
,created = ps.OrderByDescending(x=>x.created).FirstOrDefault()==null?null:ps.OrderByDescending(x=>x.created).First().created
};