2013-01-04 59 views
9

我有一個LINQ查詢,它返回的結果與我的PictureGallery類匹配。我需要將它們加載到我ViewModel但即時得到以下錯誤:如何將這些LINQ結果加載到ViewModel類中?

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

我是相當新的C#。如何將「結果」投射到我的「PictureGallery」viewmddel類中?

在此先感謝!

控制器:

//Test MediaID 
var MediaID = 75; 

//Query Results 
var Results = from g in DB.Galleries 
       join m in DB.Media on g.GalleryID equals m.GalleryID 
       where g.GalleryID == GalleryID 
       orderby m.MediaDate descending, m.MediaID descending 
       select new { g.GalleryTitle, Media = m }; 

//Create my viewmodel 
var Model = new GalleryViewModel 
{ 
    MediaID = MediaID, 
    PictureGallery = Results, //This line throws the error. 
    PictureCount = Results.Count() 
}; 

的ViewModels:

public class GalleryViewModel 
{ 
    public int? MediaID { get; set; } 
    public IEnumerable<PictureGallery> PictureGallery { get; set; } 
    public int PictureCount { get; set; } 
} 

public class PictureGallery 
{ 
    public int GalleryID { get; set; } 
    public string GalleryTitle { get; set; } 
    public int MediaID { get; set; } 
    public string MediaTitle { get; set; } 
    public string MediaDesc { get; set; } 
    public double Rating { get; set; } 
    public int Views { get; set; } 
} 

回答

16

修改你的查詢爲:

//Query Results 
var Results = from g in DB.Galleries 
       join m in DB.Media on g.GalleryID equals m.GalleryID 
       where g.GalleryID == GalleryID 
       orderby m.MediaDate descending, m.MediaID descending 
       select new PictureGallery { 
           GalleryID = g.GalleryId, 
           GalleryTitle = g.GalleryTitle, 
           MediaID = m.MediaID, 
           MediaTitle = m.MediaTitle, 
           MediaDesc = m.MediaDesc, 
           Rating = m.Rating, 
           Views = m.Views} ; 
+0

是啊是工作!謝謝 – Maddhacker24

2

您正在嘗試設置IEnumerable<PictureGallery>IQueryable<anonymous>。您需要轉換爲正確的類型:

var Model = new GalleryViewModel 
{ 
    MediaID = MediaID, 
    PictureGallery = Results 
     .Select(r => new PictureGallery { 
      GalleryID = r.Media.GalleryID, 
      GalleryTitle = r.GalleryTitle, 
      MediaID = r.Media.MediaID, 
      ... // and so on 
     }), 
    PictureCount = Results.Count() 
}; 
0

然後你可以寫 VAR列表= result.ToList();

然後通過它來查看像這樣 return View(list);

你可以在你看來像這樣 @model名單

凡視圖模型是用性能來接受查詢執行後的結果值的簡單類接受它。

您可以查看這些附件[Linq查詢,視圖模型,視圖enter image description here][1]

相關問題