[英]linq to sql mulitiple joins
我正在嘗試創建LINQ to SQL查詢,但確實很麻煩。
我有一個具有多個表的數據庫,並且可以創建一個查詢,該查詢從單個聯接中成功返回結果。 我遇到的問題是引入第二個聯接。
SQL語句很容易生成
USE InlandMarina
SELECT *
FROM Slip s LEFT JOIN Lease l ON s.id = l.slipid
WHERE GETDATE() > l.EndDate OR ISNULL(l.startdate, '') = ''
我已經生成了兩個功能性LINQ查詢,它們分別返回所需的結果,但是不能成功地將兩者結合。
var nulledSlips = from slips in theContext.Slips
join nulled in theContext.Leases on slips.ID equals nulled.SlipID into slipsNulled
from nulledEndDate in slipsNulled.Where(nulled => nulled.EndDate==null).DefaultIfEmpty()
返回未在數據庫中設置結束日期的所有發票(空),這些發票從未被租借。
from expiredSlips in theContext.Slips
join leased in theContext.Leases on slips.ID equals leased.SlipID into allSlips
from leased in allSlips
where leased.EndDate < DateTime.Today
返回租約到期的單據。
我想做的是將這兩個查詢以某種方式組合成一個查詢,該查詢返回所有從未租出或租約到期的單據。
任何幫助將不勝感激,我已經在這里待了兩天了,再也看不到森林里有樹木了。
模式是四個表。 租賃,滑移,停放,位置。 租賃PK ID FK SlipID
單據PK ID FK DockID
碼頭PK ID FK位置ID
位置PK ID
修改后的查詢為:
var expiredSlips = from slips in theContext.Slips
join nulled in theContext.Leases on slips.ID equals nulled.SlipID into slipsNulled
from nulledEndDate in slipsNulled.Where(nulled => nulled.EndDate == null).DefaultIfEmpty()
join leased in theContext.Leases on slips.ID equals leased.SlipID into allSlips
from leased in allSlips.Where(leased=> leased.EndDate < DateTime.Today).DefaultIfEmpty()
返回值:
<SlipsDTO>
<SlipID>1000</SlipID>
<Width>8</Width>
<Length>16</Length>
<DockID>1</DockID>
<WaterService>true</WaterService>
<ElectricalService>true</ElectricalService>
<MarinaLocation>Inland Lake</MarinaLocation>
<LeaseStartDate xsi:nil="true" />
<LeaseEndDate xsi:nil="true" />
</SlipsDTO>
屈服一切。 如果刪除最后一個.DefaultIfEmpty(),則會得到僅包含租約的單據的結果集。 當前或過期。
如果FK到位,通常您不必自己使用linq-to-sql進行“加入”步驟,您只需引用導航屬性即可。 另外,請記住,可以使用“ let”來定義查詢中的內容,這可能會使您更容易進行查詢。
由於FK是通過具有SlipID的租約方式進行的,因此給定的單據可能具有與之關聯的任何數量(0 .. *)的租約,盡管您的邏輯似乎表明它將僅為0或1-如果那是是的,單據上可以為空的FK LeaseID可能更有意義,但這是切線。 現在,我將繼續使用原始的SQL邏輯,即“任何關聯的租約都已過期”
var query =
from slip in context.Slips
let expiredLeases = slip.Leases.Where(lease => lease.EndDate < DateTime.Today)
where slip.Leases.Any() == false // no leases for this slip yet
|| expiredLeases.Any() // at least one associated lease is expired
select slip;
當然,您仍然可以構造不帶導航屬性的查詢,但是我發現使用生成的導航屬性而不是手動指定聯接及其條件容易,容易出錯得多:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.