Cannot implicitly convert type system linq IQueryable to system collections generic List

混江龙づ霸主 提交于 2019-12-02 09:57:20

The extension method .Select will returns a IEnumerable<TResult>, But you are trying to assign them to a business object of type ProductRegistrationViewModelVM such assignment is in valid, either you can change the type of vm to var or you have to make it as List if so the query will be like the following:

List<ProductRegistrationViewModelVM> vm =(from p in db.Products
                   join i in db.Images on p.ProductId equals i.Product_Id
                   join s in db.Specifications on p.ProductId equals s.Product_Id
                   select new ProductRegistrationViewModelVM
                   {
                       //Product
                       p.Name,
                       p.Produt_Code,
                       p.Description,
                       //Image
                       i.Image_Description,
                       i.Image_Name,
                       i.image1,
                       //Specifications
                       s.Sz_Measurement_Unit,
                       s.Size,
                       s.Wg_Measurement_Unit,
                       s.Weight,
                       s.Price_Set,
                       s.Price_Sold
                   }).ToList();

Now you can easily add another object of type ProductRegistrationViewModelVM to this since it a List of the same type. And you should do a small change in return as well. which will be like the following;

return View(vm); // No ToList is needed here since it is already a list

You create a vm like this:

ProductRegistrationViewModelVM  vm = new ProductRegistrationViewModelVM();

Then you assign an IQueryable which returns anonymous types to it. That will not pass. Then you try and add a new instance of your view model to it and that will not work either:

vm.Add(new ProductRegistrationViewModelVM());

Fix

Try this instead:

var vm = ( from p in db.Products
         join i in db.Images on p.ProductId equals i.Product_Id
         join s in db.Specifications on p.ProductId equals s.Product_Id
         select new ProductRegistrationViewModelVM
         {
            //Product
            p.Name,
            p.Produt_Code,
            p.Description,
            //Image
            i.Image_Description,
            i.Image_Name,
            i.image1,
            //Specifications
            s.Sz_Measurement_Unit,
            s.Size,
            s.Wg_Measurement_Unit,
            s.Weight,
            s.Price_Set,
            s.Price_Sold
         } );

return View( vm.ToList() );

And make sure your view accepts a Model as List<ProductRegistrationViewModelVM>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!