11

PictureGallery我有一个 LINQ 查询,它返回与我的班级匹配的结果。我需要将它们加载到我的ViewModel但我收到以下错误:

无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少演员表?)

我对 C# 比较陌生。如何将“结果”投射到我的“图片库”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()
};

视图模型:

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

3 回答 3

18

将您的查询改写为:

//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} ;
于 2013-01-04T22:51:30.783 回答
2

您正在尝试将 an 设置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()
};
于 2013-01-04T22:49:35.690 回答
0

然后你可以写 var list = result.ToList();

然后像这样将它传递给视图 return View(list);

您可以像 @model List 一样在您的视图中接受它

其中 ViewModel 是一个简单的类,具有在查询执行后接受结果值的属性。

您可以查看这些附件[Linq 查询、查看模型、查看在此处输入图像描述][1]

于 2015-11-24T13:04:07.503 回答