2012-03-03 72 views
0

我的LINQ心不是最好的,也不是我的SQL,但我嘗試做LINQ是這樣的(同類僞代碼)如何在Linq中執行此SQL? (LEFT OUTER JOIN W /日期)

select * from CarePlan c 
-- only newest Referral based on r.Date (if more than one exists) 
left outer join Referral r on r.CarePlanId = c.CarePlanId 
where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0'  

的數據看起來像此:

  • 患者能夠有一堆careplans的
  • 每個careplan可以具有0到n的推薦(I想每careplan最新推薦 - 如果存在的話)

想回careplans列表爲每位患者(無論他們是否有轉診或沒有,如果有一個以上的推薦 - 抓住最新的一個)的任何幫助球員

回答

1

謝謝LINQ使用DefaultIfEmpty實現左外連接 - 在http://msdn.microsoft.com/en-us/library/bb397895.aspx

例子假設轉診不在護理計劃,所以你要加入兩個集合在一起的(可能是空的)收集...

您的查詢會是這樣的:

取得每個護理計劃的最新推介:

var latestReferrals = from r in referrals 
     group r by r.CarePlanId into lr 
     select new { CarePlanId = lr.Key, LatestReferral = lr.OrderByDescending(lrd => lrd.Date).First()}; 

找到的綜合信息:

var q = from c in CarePlan 
     where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0' 
     join lr in latestReferrals on c.CarePlanId equals lr.CarePlanId into gj 
     from subReferral in gj.DefaultIfEmpty() 
     select new { CarePlanId = c.CarePlanId, LatestReferral = (subReferral == null) ? null : subReferral.LatestReferral }; 

根據您是否希望多推薦性或只是幾個你可能會或可能不希望整個推薦對象在第二部分或只是提取相關的屬性。

您可能可以將這些組合成單個查詢,但爲了便於閱讀,可能會更容易將它們分開。如果有一個聯合解決方案,您還應該比較兩種方法的性能。

編輯:從照顧病人加盟/其他表見註釋如果患者是從推薦,因爲你正在做幾左外連接加入(按評論),那麼它的更復雜的計劃

。所以切換到稍微更簡潔的語法:

var combined = from c in carePlans 
where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0' 
from lr in latestReferral.Where(r => r.CarePlanId == c.CarePlanId).DefaultIfEmpty() 
from p in patients.Where(patient => patient.PatientId == ((lr != null) ? lr.LatestReferral.PatientId : -1)).DefaultIfEmpty() 
select new { c.CarePlanId, PatientName = (p == null) ? "no patient" : p.PatientName, LatestReferral = (lr == null) ? null : lr.LatestReferral }; 
+0

感謝您的聯繫 - 但我的問題的一部分是,我有根據日期,以獲得最新的引薦下,它可能會或可能不存在 - 這是確定 – Jerrold 2012-03-05 21:53:14

+0

已更新,以查找最新推薦 – kaj 2012-03-06 12:45:53

+0

偉大的工作,但如果它們存在,我可以在哪裏/如何加入多個基於推薦的表? 例如推薦 - >患者 - >用戶,以防我想獲得User.Name或其他東西 – Jerrold 2012-03-06 22:12:16