2017-01-02 93 views
0

我正在努力構建一個提供單個最小值的linq查詢。但是,我一直得到錯誤的最小值。我確定這是一個連接問題,但我無法獲得一個外連接的工作。我已經嘗試了一些基於其他職位的外部連接,但無法做任何工作。我不確定我需要外部連接來完成這項工作。我想我已經嘗試過,我認爲我可以組合每一個組合。Linq查詢沒有給出預期的結果

這裏是我開始查詢:

(from r in Results 
    join entry in Entries on r.EntryId equals entry.EntryId 
    join entryEvent in EntryEvents on entry.EntryId equals entryEvent.EntryId 
    join eswimmer in EntrySwimmers on entry.EntryId equals eswimmer.EntryId 
    where eswimmer.SwimmerId == 12027 && entryEvent.EventNumberId == 1233 
    select r.Time) 
.Min(); 

外連接嘗試:

from r in Results 
join en in Entries on r.EntryId equals en.EntryId 
join ev in EntryEvents on en.EntryId equals ev.EntryId into evJoined 
join s in EntrySwimmers on en.EntryId equals s.EntryId into sJoined 
from ev in evJoined.DefaultIfEmpty() 
from s in sJoined.DefaultIfEmpty() 
where (s.SwimmerId == 12027 && ev.EventNumberId == 1233) 
select r.Time; 

的問題是,我得到的所有結果最小值爲游泳而不是該游泳者的最小值和特定事件。

的階級結構是這樣的:

結果

public int ResultId 
public int EntryId 
public ICollection<Entry> Entry 
public int EntryEventId 
public ICollection<EntryEvent> EntryEvent 
public TimeSpan Time 

public int EntryId 
public ICollection<EntrySwimmer> EntrySwimmers 
public Result Results 
public ICollection<EntryEvent> EntryEvents 

EntryEvents

public int EntryEventId 
public int EventNumberId 
public EventNumber EventNumbers 
public int EntryId 
public Entry Entry 

EntrySwimmers

public int EntryId 
public Entry Entries 
public int SwimmerId 
public Swimmer Swimmers 

我還在學習關於linq,連接等等,所以感謝解釋。先謝謝你!

+1

首先在T-SQL中編寫一個工作查詢,然後從那裏開始向後工作。 – Nkosi

+0

我在SQL中得到了相同的結果。 – Wyatt

+0

這個模特好嗎? 'Entry'有許多'EntryEvents' *和*許多'EntrySwimmers'。你如何將游泳者連接到特定的'EntryEvent'? –

回答

0

您已經擁有了導航屬性映射所以基本上你不需要任何連接,因爲你的ORM將覆蓋爲你:

var min = Results 
      .Include(x => x.Entry.Select(y => y.EntrySwimmers)) //here you should rename Entry to Entries ideally in your result class 
      .Include(x => x.Entry.Select(y => y.EntryEvents)) 
      .Where(x => x.Entry.EntrySwimmers.Any(y => y.SwimmerId == 12027) && x.EntryEvents.Any(y => y.EventNumberId == 1233))    
      .Min(x => x.Time); 

不知道爲什麼你有兩個在結果和條目,雖然活動。

+0

我試過你所擁有的東西,但不斷收到ICollection 沒有包含EntrySwimmers的定義的消息,而Result沒有包含EntryEvents的定義。 – Wyatt

+0

然後,你應該檢查你的映射,看看有什麼不對。您必須檢查您的映射是否完全按照數據庫設置。一對一,一對多關係 – Yaser

+0

我修改了where子句爲:Where(x => x.Entries.Any(y => y.EntrySwimmers.Any(e => e.SwimmerId == swimmerid)) && x.EntryEvent.Any(y => y.EventNumberId == eventid))''但我沒有收到任何東西,只是00:00:00.00作爲輸出。我檢查了映射,他們對我看起來還不錯。我應該特別尋找什麼? – Wyatt

相關問題