2012-10-21 178 views
0

我有如下表多在實體框架連接查詢

任務
ID |名稱| proj_id
1 | task1 | 1
2 | task2 | 1
3 | task3 | 1

項目
ID |名稱
1 |樣品proj1
2 |演示項目

budget_versions
id | VERSION_NAME | proj_id
1 | 50 | 1

預算
ID |成本| budget_version_id | task_id
1 | 3000 | 1 | 2
2 | 5000 | 1 | 1

我需要加入這些表得到的結果如下使用實體框架

TASK_ID | task_name | project_id | budget_version | budget_id |成本
1 | task1 | 1 | 1 | 2 | 5000
2 | task2 | 1 | 1 | 1 | 3000
3 | task3 | 1 | NULL | NULL | NULL

選擇tsk.id,tsk.name,tsk.project_id,bgtver.id,bgt.id,bgt.cost 從任務tsk 左外連接bgtver BUDGET_VERSIONS上tsk.project_id = bgtver.project_id 左外連接收支BGT 上bgtver.id = bgt.budget_version_id和tsk.id = bgt.task_id 其中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 ());

+0

http://stackoverflow.com/questions/21051612/entity-framework-join-3-tables –

回答

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 
       }; 

Here的你怎麼做左外的LINQ連接。