Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load these LINQ results into my ViewModel class?

I have a LINQ query which returns results that match up with my PictureGallery class. I need to load them into my ViewModel but im getting the following error:

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

I'm rather new at C#. How do I cast "Results" into my "PictureGallery" viewmddel class?

Thanks in advance!

Controller:

//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; }
}
like image 912
Maddhacker24 Avatar asked Jan 04 '13 22:01

Maddhacker24


2 Answers

Rephrase your query as:

//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} ;
like image 177
Hamlet Hakobyan Avatar answered Oct 21 '22 05:10

Hamlet Hakobyan


You are trying to set an IEnumerable<PictureGallery> to an IQueryable<anonymous>. You need to transform to the correct type:

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()
};
like image 34
Paul Fleming Avatar answered Oct 21 '22 04:10

Paul Fleming