2015-04-15 104 views
1

我需要將最近的操作(如果有的話)關聯到每個節點。 SQL查詢波紋管爲我做這個:LINQ中的級聯左連接

select n.*, o.* from Nodes n 
left outer join (
    select min(s.ActionAt) as ActionAt, min(s.Ahead) as Ahead, s.NodeId 
    from SuggestedActions s 
    group by s.NodeId 
) o1 
    on o1.NodeId=n.Id 
left outer join SuggestedActions o 
    on o.NodeId=o1.NodeId and o.ActionAt=o1.ActionAt and o.Ahead=o1.Ahead 

但我不能用LINQ制定相同的查詢。我已經離開加入哪個選擇最近的行動,我不知道如何繼續加入更多的數據:

from node in db.Nodes 
join no in db.SuggestedActions on node.Id equals no.NodeId into no1 
from o1 in no1.DefaultIfEmpty() 
group o1 by node.Id into go1 
select new { 
    NodeId = go1.Key, 
    ActionAt = go1.Min(c => c.ActionAt), 
    Ahead = go1.Min(c => c.Ahead) 
} ... 

回答

1

有這是一個嘗試,它不是測試,但可能給你一個方向:

var nodeActions = from node in db.Nodes 
    join action in db.SuggestedActions on node.Id equals action.NodeId into actions 
    from action in actions.DefaultIfEmpty() 
    select new { node, action }; 

var minNodes = from nodeAction in nodeActions 
    group nodeAction by nodeAction.node.Id 
    into groupedActions 
    select new 
    { 
     NodeId = groupedActions.Key, 
     ActionAt = groupedActions.Min(c => c.action.ActionAt), 
     Ahead = groupedActions.Min(c => c.action.Ahead) 
    }; 

var result = from minNode in minNodes 
    join nodeAction in nodeActions on new { Id = minNode.NodeId, minNode.ActionAt, minNode.Ahead } 
     equals new { nodeAction.node.Id, nodeAction.action.ActionAt, nodeAction.action.Ahead } into nodeActionJ 
    from action in nodeActionJ 
    select action; 
+0

感謝您的想法:我不知道我可以將LINQ查詢拆分爲多個IQueryable,並且EF將發出單個SQL命令。 PF – pf1957