无法将类型'System.Linq.IQueryable <anonymoustype#1>'隐式转换为'System.Collections.Generic.IEnumerable <subcateviewmodel>'</subcateviewmodel> </anonymoustype#1>

时间:2014-03-21 04:38:04

标签: linq asp.net-mvc-4

当我尝试加入三个表ProductPhotoProductProductProductPhoto时,我遇到了这个问题。我尝试了很多案例,但没有成功。有人可以帮我摆脱这个吗?谢谢你的回复!

private IEnumerable<SubCateViewModel> GetSubProduct()
            {
                var context = new AdvenDBEntities();
                var subcate = (from a in context.ProductPhotoes
                              join b in context.ProductProductPhotoes on a.ProductPhotoID equals b.ProductPhotoID
                              join c in context.Products on b.ProductID equals c.ProductID
                              join d in context.ProductSubcategories on c.ProductSubcategoryID equals d.ProductSubcategoryID
                              select new
                              {
                                  a.ProductPhotoID,
                                  a.ThumbnailPhotoFileName,
                                  c.ProductID,
                                  c.Name,
                                  d.NameofBike,
                                  d.isSelected,
                              }).AsQueryable();
                         return subcate;
            }

2 个答案:

答案 0 :(得分:3)

尝试以下代码伙伴..

private IEnumerable<SubCateViewModel> GetSubProduct()
                {
                    var context = new AdvenDBEntities();
                    var subcate = (from a in context.ProductPhotoes
                                  join b in context.ProductProductPhotoes on a.ProductPhotoID equals b.ProductPhotoID
                                  join c in context.Products on b.ProductID equals c.ProductID
                                  join d in context.ProductSubcategories on c.ProductSubcategoryID equals d.ProductSubcategoryID
                                  select new SubCateViewModel
                                  {
                                     ProductPhotoID =  a.ProductPhotoID,
                                      ThumbnailPhotoFileName = a.ThumbnailPhotoFileName,
                                     ProductID = c.ProductID,
                                      Name = c.Name,
                                      NameofBike = d.NameofBike,
                                      isSelected = d.isSelected,
                                  });
                             return subcate.AsEnumerable();
                }

答案 1 :(得分:1)

问题是您的匿名类型列表无法转换为SubCateViewModel列表。

为什么你使用匿名类型呢?只需在查询中创建一个新的SubCateViewModel实例(选择SubCateViewModel而不是匿名类型)。

而不是使用LINQ中的匿名类型:

select new SubCateViewModel 
{
// Set class variables here...
}