2016-05-30 117 views
2

我有如下表LINQ的選擇tablemapping(實體框架)

**Track Table** 
+---------------+---------------+--------------------+ 
| TrackId  | TrackName |  Path   | 
+===============+===============+====================+ 
| 1    | jb   | http://domain/1.mp3| 
+---------------+---------------+--------------------+ 
| 2    | remix   | http://domain/2.mp3| 
+---------------+---------------+--------------------+ 

**Favorite Table** 
    +---------------+---------------+--------------------+ 
    | favoriteId | ProfileId  |  TrackId  | 
    +===============+===============+====================+ 
    | 10   | 2130   | 1     | 
    +---------------+---------------+--------------------+ 
    | 11   | 2132   | 2     | 
    +---------------+---------------+--------------------+ 

我需要選擇軌道成一種模式,我必須包括布爾場IsFavorite。 現在我的邏輯如下:

1.Select Tracks 
2.Select all favorites by profile 
3.Iterate to both list and fill field "IsFavorite" 

有沒有什麼更好的方法,可以計算出相同?

以下是我目前的邏輯代碼提前

Var ActiveTracks = jukeboxTrackService.GetActiveTracks(); 
var UserFavorites = jukeboxTrackService.GetFavoritesByProfile(ProfileId); 
foreach (var item in ActiveTracks) 
{ 
    foreach (var fav in UserFavorites) 
    { 
     if (item.JukeBoxTrackId == fav.TrackId) 
     { 
      item.IsFavorite = true; 
     } 
    } 
} 

return ActiveTracks ; 

感謝。

+0

您可以使用內使用LINQ http://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql加盟 –

回答

2
(from tr in ActiveTracks 
join usrfav in UserFavorites on tr.TrackId equals usr.TrackId into UsrTracks 
from usrtr in UsrTracks.DefaultIfEmpty() 
select new Track 
{ 
    IsFavorite = (usrfav.TrackId == null) ? false : true 
}