0

我有以下表格

tasks  
id | name   | proj_id  
1  | task1  | 1  
2  | task2  | 1  
3  | task3  | 1  


projects  
id | name  
1  | sample proj1  
2  | demo project  

budget_versions  
id | version_name| proj_id  
1  | 50          | 1  

budgets  
id | cost  | budget_version_id | task_id  
1  | 3000  | 1                 | 2  
2  | 5000  | 1                 | 1  

我需要使用实体框架加入这些表以获得如下结果

task_id | task_name | project_id | budget_version | budget_id | cost   
1       | task1     | 1          | 1              | 2         |5000  
2       | task2     | 1          | 1              | 1         |3000  
3       | task3     | 1          | NULL           | NULL      |NULL   
select tsk.id,tsk.name, tsk.project_id, bgtver.id, bgt.id, bgt.cost 
from TASK tsk
left outer join BUDGET_VERSIONS bgtver
on tsk.project_id= bgtver.project_id
left outer join BUDGETS bgt
on bgtver.id = bgt.budget_version_id  and tsk.id = bgt.task_id
where bgtver.id = 1

这是我迄今为止尝试过的

var budgetlists = _worker.Budgets.Get().GroupJoin(
    _worker.BudgetVersions.Get(),
    rb => rb.budget_version_id, 
    rbv => rbv.id,
    (rb, rbrbv) => new {rb, rbrbv}
).SelectMany(
    @t => @t.rbrbv.DefaultIfEmpty()
).GroupJoin(
    _worker.Tasks.Get(), 
    rbrbv => rbrbv.id, 
    tsk => tsk.id,
    (rbrbv, tskrb) => new {rbrbv, tskrb}
).SelectMany(
    @p => @p.tskrb.DefaultIfEmpty());
4

1 回答 1

1

这应该有效:

var result = from tsk in tasks
                join bv in budget_versions on tsk.proj_id equals bv.proj_id into g1
                from bgtver in g1.DefaultIfEmpty()
                join b in budgets on new { bgtver_id = bgtver.id, tsk.id } equals new { bgtver_id = b.budget_version_id, id = b.task_id } into g2
                from bgt in g2.DefaultIfEmpty()
                select new Result 
                { 
                    task_id = tsk.id, 
                    task_name = tsk.name, 
                    project_id = tsk.proj_id, 
                    budget_version = bgtver.id, 
                    budget_id = bgt == null ? (int?)null : bgt.id, 
                    cost = bgt == null ? (int?)null : bgt.cost 
                };

下面介绍如何在 LINQ 中进行左外连接。

于 2012-10-21T05:38:13.863 回答