c# - 如何将这些 LINQ 结果加载到我的 ViewModel 类中?

标签 c# asp.net asp.net-mvc asp.net-mvc-3 linq

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

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

我是 C# 的新手。如何将“结果”转换到我的“PictureGallery”viewmddel 类中?

提前致谢!

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

View 模型:

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

最佳答案

将您的查询改写为:

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

关于c# - 如何将这些 LINQ 结果加载到我的 ViewModel 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14166245/

相关文章:

c# - MySQL 和事务不回滚

c# - 解码 XML 时 base64 字符串中的无效字符

c# - ASP.NET Web API 和 [Serializable] 类

asp.net - 从vs2012发布Web应用程序项目到本地目录

asp.net - MVC 路由与服务路由冲突

c# - IIS 替换部分 url

c# - 比较没有年份的 DateTime

c# - C# 中的可事务对象?

asp.net - 51°.mobi 的替代品?

c# - asp.net mvc3 302 在 $.get 调用上发现错误