不能隐式转换类型“System.Linq.IQueryable”

时间:2022-02-04 16:34:38

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

我的c#项目出错了,这让我头疼。错误的是:

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

Here's my LINQ querys:

这是我的LINQ查询:

//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:

在GalleryResults下出现的squigally行错误:

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

1 个解决方案

#1


7  

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我认为他的答案是正确的,他的解决方案摆脱了错误信息。所以我又把它发布了:

Ufuk Hacıoğulları's answer;

Ufuk Hacıoğulları的回答;

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

您正在投射一个匿名类型的序列,而不是Gallery。在select语句中实例化Gallery对象,它应该可以工作。

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 };

#1


7  

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我认为他的答案是正确的,他的解决方案摆脱了错误信息。所以我又把它发布了:

Ufuk Hacıoğulları's answer;

Ufuk Hacıoğulları的回答;

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

您正在投射一个匿名类型的序列,而不是Gallery。在select语句中实例化Gallery对象,它应该可以工作。

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 };