无法隐式转换类型'System.Linq.IQueryable <anonymoustype#1>'</anonymoustype#1>

时间:2013-01-02 21:05:19

标签: c# asp.net-mvc linq

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

1 个答案:

答案 0 :(得分:7)

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

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