2

我在我的 C# 项目中遇到一个错误,这让我很头疼。错误是:

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

这是我的 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 };

这是我的视图模型。

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

在 GalleryResults 下出现波浪线错误:

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

1 回答 1

7

Ufuk Hacıoğulları 已发布答案并在几分钟后将其删除。我认为他的回答是正确的,他的解决方案摆脱了错误信息。所以我再次发布它:

Ufuk Hacıoğulları 的回答;

您正在投影一系列匿名类型而不是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 };
于 2013-01-02T21:21:45.383 回答