2012-08-09 52 views
0

短查詢任何人能告訴我最短的查詢這樣的:這個漫長的

 var guestpartyids = db.CeremonyGuestParties.Where(p => p.CeremonyId == id) 
          .Select(p => p.GuestPartyId); 
     List<GuestParty> guestparties = new List<GuestParty>(); 
     foreach (var party in guestpartyids) 
     { 
      guestparties.Add(db.GuestParties.Single(p => p.Id == party)); 
     } 

回答

2

這應該這樣做。

guestparties.AddRange(
    from cgp in db.CeremonyGuestParties 
    where cgp.CeremonyId == id 
    join gp in db.GuestParties on cgp.GuestPartyId equals gp.Id 
    select gp 
); 

請注意,這將導致一次數據庫調用,因爲您的代碼將導致1 + N查詢。但是它不能確保只有一個匹配的ID,就像Single()那樣。無論如何,這應該在數據庫上執行,而不是在代碼中執行。

0

如何:

List<GuestParty> guestparties = from cgp in db.CeremonyGuestParties. 
           Where cgp.CeremonyId .id == id) 
           select cgp.Guestparties.ToList(); 
相關問題