Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>'

11,775

Ufuk Hacıoğulları has posted an answer and deleted it a few minutes later. I think his answer was correct and his solution gets rid of the error message. So I'm posting it again:

Ufuk Hacıoğulları's answer;

You are projecting a sequence of anonymous type instead of Gallery. Just instantiate Gallery objects in your select statement and it should work.

var GalleryResults = from g in DB.Galleries
                     join m in DB.Media on g.GalleryID equals m.GalleryID into gm
                     where g.GalleryID == 100
                     select new Gallery { GalleryTitle = g.GalleryTitle, Media = gm };
Share:
11,775
Maddhacker24
Author by

Maddhacker24

I'm a web developer looking to learn the new latest and greatest technologies.

Updated on June 17, 2022

Comments

  • Maddhacker24
    Maddhacker24 almost 2 years

    Im getting an error in my C# project which is causing me a headache. The error is:

    Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>'
    to System.Collections.Generic.IEnumerable<KST.ViewModels.Gallery>'.
    

    Here's my LINQ querys:

    //Get Single Picture
    var PictureResults = (from m in DB.Media where m.MediaID == 450 select m).SingleOrDefault();
    
    //Get Gallery Pictures and Gallery Title
    var GalleryResults = from g in DB.Galleries
                         join m in DB.Media on g.GalleryID equals m.GalleryID into gm
                         where g.GalleryID == 100
                         select new { g.GalleryTitle, Media = gm };
    

    Here's my viewmodels.

    public class GalleryViewModel
    {
        public Media Media { get; set; }
        public IEnumerable<Gallery> Gallery { get; set; }
    }
    
    public class Gallery
    {
        public string GalleryTitle { get; set; }
        public int MediaID { get; set; }
        public int GalleryID { get; set; }
        public string MediaGenre { get; set; }
        public string MediaTitle { get; set; }
        public string MediaDesc { get; set; }
    }
    

    The squigally line error occurs under GalleryResults:

    //Create my viewmodel
    var Model = new GalleryViewModel
    {
        Media = PictureResults,
        Gallery = GalleryResults
    };