2013-10-12 112 views
5

這樣先進的投影查詢

using (var db = new SmartContext()) 
{ 
    var MyQuery = from idr in db.ID_SB 
        join tk in db.Track_SB on idr.MB_Track_ID equals tk.MB_TrackID 
        join talr in db.Track_Album_Reln on tk.MB_TrackID equals talr.MB_Track_ID 
        join tal in db.Album_SB on talr.MB_AlbumID equals tal.MB_Release_ID 
        orderby idr.Last_played descending 
        select new 
        { 
         mb = tk.MB_TrackID, 
         Hash = idr.Hash, 
         Title = tk.Title, 
         Album = tal.Album_Name, 

         Times_Played = idr.Times_played, 
         Last_Played = idr.Last_played 

        }; 

    string artist = ""; 
    var list = new[] { new { Hash = "", Title = "", Album = "", Artist = "", Times_Played = "", Last_Played = ""}}.ToList(); 
    list.Clear(); 
    foreach (var q in MyQuery) 
    { 
     int i = 0; 
     var art = db.Track_Artist_Reln.Where(a => a.MB_Track_ID == q.mb); 
     foreach (var a in art) 
     { 
      var tart = db.Artist_SB.Where(ar => ar.MB_Artist_ID == a.MB_ArtistID).Select(ar => ar.Artist_Name); 
      foreach (var tar in tart) 
      { if (i != 0) { artist = artist + ", " + tar; } else { artist = tar; i++; } } 
     } 
     list.Add(new 
     { 
      Hash = q.Hash.ToString(), 
      Title = q.Title.ToString(), 
      Album = q.Album.ToString(), 
      Artist = artist.ToString(), 
      Times_Played = q.Times_Played.ToString(), 
      Last_Played = q.Last_Played.ToString(),    
      }); 
    } 


    ListView1.ItemsSource = list; 
} 

的任何更好的辦法是爲這個,因爲它會消耗大量的時間沒有更好的辦法

這個代碼在此我要服務於目的

檢索

  • 哈希
  • 標題
  • ALBUMNAME
  • 藝術家(包含所有藝術家在單行領域藝術家的那首歌)
  • 時報發揮
  • 最後出場

我所有的一切能得到的只是通過讓參加一切除了藝術家的名字

還有很多可能的關係 主表ID_SB,Track_SB,Album_SB,Artist_SB 其他都是關係storin克兩個表的主鍵

+0

一個快速的事情,以改善它,有它返回的第一個查詢一個集合移動兩個foreach循環嵌套的數據庫查詢到主查詢。這將導致它有很少的旅行到數據庫。 –

+0

您應該擺脫* _Reln表,而EF在多年以來直接支持多對多關係。 –

回答

0

內環可以使用string.Join(…).SelectMany()弄平嵌套列表(真IEnumerable)被替換成一個:

var artist = string.Join(", ", 
         db.Track_Artist_Reln 
          .Where(a => a.MB_Track_ID == q.mb) 
          .SelectMany(a => db.Artist_SB 
               .Where(ar => ar.MB_Artist_ID == a.MB_ArtistID) 
               .Select(ar => ar.Artist_Name))); 

除了手動轉換枚舉到一個列表的您可以使用.ToList()

var list = MyQuery.Select(q => new{ 
     Hash = q.Hash.ToString(), 
     Title = q.Title.ToString(), 
     Album = q.Album.ToString(), 
     Artist = string.Join(", ", 
          db.Track_Artist_Reln 
           .Where(a => a.MB_Track_ID == q.mb) 
           .SelectMany(a => db.Artist_SB 
                .Where(ar => ar.MB_Artist_ID == a.MB_ArtistID) 
                .Select(ar => ar.Artist_Name))), 
     Times_Played = q.Times_Played.ToString(), 
     Last_Played = q.Last_Played.ToString(),    
     }.ToList();