0

I have written the following linq query in .net mvc project:

        var list = (from i in db.Inventories
                    join o in db.SalesOrders on i.OrderId equals o.IID
                    join c in db.CustomerSuppliers on i.SLCode equals c.IID
                    join p in db.SalesPersons on o.SalesPerson equals p.IID into ps
                    from p in ps.DefaultIfEmpty()
                    where i.IID == id
                    select new SalesViewModel
                    {
                        IID = i.IID,
                        DocNo = i.DocNo,
                        DocDt = i.DocDt,
                        RefNo = i.RefNo,
                        RefDate = i.RefDate,
                        DocType = type,
                        DocDesc = i.DocDesc,
                        SLCode = i.SLCode,
                        OrderId = o.OrderId,
                        ClientName = c.Name,
                        SalesPerson = p.Name
                    });



        return View(list);

I define model inside my view like:

@model WebApp.Models.SalesViewModel

When I run the project I am getting the following error:

"The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[WebApp.Models.SalesViewModel]', but this dictionary requires a model item of type 'WebApp.Models.SalesViewModel'."

I am returning the SalesViewModel model in my query select new SalesViewModel. Any Clue?

Hary
  • 5,690
  • 7
  • 42
  • 79
Partha
  • 469
  • 2
  • 14
  • 32

1 Answers1

0

The error clearly says that the object returned from the Controller to the view is not of type WebApp.Models.SalesViewModel.

Try get the the DBQuery result to SalesViewModel by using FirstOrDefault().

SalesViewModel list = (from i in db.Inventories
                    join o in db.SalesOrders on i.OrderId equals o.IID
                    join c in db.CustomerSuppliers on i.SLCode equals c.IID
                    join p in db.SalesPersons on o.SalesPerson equals p.IID into ps
                    from p in ps.DefaultIfEmpty()
                    where i.IID == id
                    select new SalesViewModel
                    {
                        IID = i.IID,
                        DocNo = i.DocNo,
                        DocDt = i.DocDt,
                        RefNo = i.RefNo,
                        RefDate = i.RefDate,
                        DocType = type,
                        DocDesc = i.DocDesc,
                        SLCode = i.SLCode,
                        OrderId = o.OrderId,
                        ClientName = c.Name,
                        SalesPerson = p.Name
                    }).FirstOrDefault();
Hary
  • 5,690
  • 7
  • 42
  • 79