无法隐式转换类型,存在显式转换(是否缺少强制转换?

我已经设置了一个ViewModel(以前使用ViewBag),但我在以下代码中遇到了错误,我已经研究了它,但个人无法找出我的问题:


public ActionResult Index(string category, string search)

    {

        ProductIndexViewModel viewModel = new ProductIndexViewModel();

        var products = db.Products.Include(p => p.Category);


        if (!String.IsNullOrEmpty(search))

        {

            products = products.Where(p => p.Name.Contains(search) ||

                    p.Description.Contains(search) ||

                    p.Category.Name.Contains(search));


            viewModel.Search = search;


        }


        viewModel.CatsWithCount = from matchingProducts in products

                                  where matchingProducts.CategoryID != null

                                  group matchingProducts by

                                  matchingProducts.Category.Name into

                                  catGroup

                                  select new CategoryWithCount()

                                  {

                                      CategoryName = catGroup.Key,

                                      ProductCount = catGroup.Count()

                                  };


        if (!String.IsNullOrEmpty(category))

        {

           products = products.Where(p => p.Category.Name == category);

        }


        viewModel.Products = products;

        return View(viewModel);

    }

错误发生在该行的底部:


viewModel.Products = products;

确切的错误是


“无法将类型隐式转换为 。存在显式转换(您是否缺少强制转换?)”'System.Linq.IQueryable<OnlineStore.Models.Product>''System.Linq.IQueryable<OnlineStore.ViewModels.ProductIndexViewModel>'


我对使用Visual Studio非常陌生,只是想知道我必须做些什么来修复这个错误。


慕码人2483693
浏览 333回答 2
2回答

蛊毒传说

问题出在我的ProductIndexViewModel类中。我有public&nbsp;IEnumerable<ProductIndexViewModel>&nbsp;Products&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}而不是public&nbsp;IEnumerable<Product>&nbsp;Products&nbsp;{&nbsp;get;&nbsp;set;&nbsp;}感谢所有回答的人。

蝴蝶刀刀

你在课堂上看起来错了ProductsProductIndexViewModelpublic class ProductIndexViewModel{&nbsp; &nbsp; public IQueryable<ProductIndexViewModel> Products { get; set; }Products是一个,它实际上没有意义,可能应该是一个或IQueryableList<T>IEnumerable<T>例public List<ProductIndexViewModel> Products { get; set; }通用参数看起来是错误的,它可能应该是或一些ViewModel,就像在ViewModel的情况下,你需要/Project到它ProductProductViewModelSelect你可能应该在结果上打电话ToList例viewModel.Products = products.ToList();
打开App,查看更多内容
随时随地看视频慕课网APP