2011-10-20 98 views
2

我想將一個複雜的(而且很冒險的)動態SQL查詢轉換成一個LINQ查詢。LINQ丟棄結果

我到目前爲止以下LINQ查詢:

var results = (
    from c in Customers 
    from d in MonthCalendar 
     join f in Facilities on c.CustomerCode equals f.CustomerCode 
     join p in ProjectedCashFlows on f.FacilityId equals p.FacilityId into pj 
       from p in pj.DefaultIfEmpty()      
     where d.ExpectedYear == currentYear 
       && f.FacilityStatusId == 1 
       && (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear) 
       && (p.ExpectedMonth == null || d.ExpectedMonth == p.ExpectedMonth) 
       && c.PrimaryArmId == userId 
       && (p.ProjectedCashFlowStatusId == null || p.ProjectedCashFlowStatusId != 4) 
     select new 
      { 
       CustomerCode = c.CustomerCode, 
       CustomerName = c.CustomerName, 
       FacilityId = f.FacilityId, 
       FacilityDescription = f.FacilityProductDescription, 
       FacilityCurrency = f.FacilityCurrencyId, 
       FacilityLimit = f.Limit, 
       ExpectedYear = d.ExpectedYear, 
       ExpectedMonth = d.ExpectedMonth, 
       ExpectedAmount = p == null ? 0 : (double)p.ExpectedAmount 

      } 
      ); 

我試圖找回從具有與Facilities表中的一個一對多的關係Customer表的詳細信息。然後我試圖找回地處ProjectedCashFlows

我遇到的問題是,查詢應該無論在ProjectedCashFlows表中是否存在任何值,返回所有CustomerFacilites信息的任何細節。

不幸的是,這個查詢沒有這樣做 - 當ProjectedCashFlows表中的工具存在時,它只返回CustomerFacilities信息。我已經使用MonthCalender表列出了當年的每個月。

相關的表信息是:

客戶

  • CustomerCode
  • 客戶名稱
  • PrimaryArmId

設施

  • CustomerCode
  • FacilityId
  • FacilityCurrencyId
  • FaciliyLimit
  • FacilityDescription

ProjectedCashFlows

  • CustomerCode
  • FacilityId
  • ExpectedYear
  • ExpectedMonth
  • ExpectedAmount
  • ProjectedCashFlowStatusId

MonthsCalendar

  • ExpectedMonth
  • ExpectedYear

例如,我有一個具有在Facilities表4行的客戶然而,這些設施2不這麼不顯示它們出現在ProjectedCashFlows表。

如果條目不存在ProjectedCashFlows應採取的ExpectedMonth & ExpectedYear從CalendarMonths表,爲ExpectedAmount返回0,並從Facilities表使用FacilityId。

正如你可能工作了,我剛開始使用LINQ。

任何人都可以在正確的方向戳我嗎?

回答

2

查詢使用p假設它非空

where d.ExpectedYear == currentYear 
     && f.FacilityStatusId == 1 
     && (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear) 
     // etc 

但是你用過DefaultIfEmpty()這在邏輯上與單個空值創建一個序列時,有沒有ProjectedCashFlows。

所以基本上你需要的東西,如:

where d.ExpectedYear == currentYear 
     && f.FacilityStatusId == 1 
     && (p == null || 
      ((p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear) 
      // etc 
     ))