var query = from r in db.Resource
join c in db.ResourceProjectedCapacity on r.ID equals c.ResourceID into ps
from c in ps.DefaultIfEmpty(null)
join p in db.Project on c.ProjectID equals p.ID
select new
{
Capacity = c,
Resource = r,
Project = p
};
我有这个linq查询,但它只返回在ResourceProjectedCapacity表上有匹配行的资源。如何获取所有资源,如果没有匹配的记录,则Capacity对象为null?
答案 0 :(得分:1)
from i in db.Resource
let c = db.ResourceProjectedCapacity.Where(cc => i.id == cc.ResourceID).FirstOrDefault()
let p = db.Project.Where(pp => c.ProjectID == pp.ID).FirstOrDefault()
select new
{
Capacity = C,
Resource = i,
Project = p
}
尝试上面的代码
答案 1 :(得分:1)
我认为次要内部连接会弄乱它上方的左外连接。我认为解决这个问题的一种方法是将连接分解为单独的查询,然后将连接保留在该连接上,如下所示:
var subquery = from c in db.ResourceProjectedCapacity
join p in db.Project on c.ProjectID equals p.ID
select new { c, p };
var query = from r in db.Resource
join c in subquery on r.ID equals c.c.ResourceID into ps
from c in ps.DefaultIfEmpty(null)
select new
{
Capacity = c.c,
Resource = r,
Project = c.p
};
请不要担心,它不会执行两个数据库查询,只有在使用query
评估.ToList()
之后,它才会针对您的数据库执行这一点。