Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Specific Columns from Entitey Framework Query While Utilizing MVC [duplicate]

Tags:

c#

asp.net-mvc

I’m new to using both Entity Framework and MVC, but not new to programming. I am working with a large table and I want to return selected columns of the query back to the view and list them. The basic query is as follows:

public class EmployeeController : Controller
{
    private ADPEntities db = new ADPEntities();

    // GET: /Employee/
    public ActionResult Index()
    {
        var tblEmployeeADPs = db.tblEmployeeADPs
            .Where(p => p.Status == "Active")
            .Select(p => new UserViewModel.USerViewModelADP
            {
                Status = p.Status,
                FirstName = p.FirstName,
                LastName = p.LastName,
                SSN = p.SSN
            });

        return View(tblEmployeeADPs.ToList());
    }
}

I created a basic C# class to strongly type the results (i.e. UserViewModel) and I still get an error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[UserViewModel.USerViewMode‌​lADP]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[DysonADPTest.Models‌​.tblEmployeeADP]'.

when I execute the page.

I’m not sure what I’m missing, as I was sure that (cobbling what I’ve read) that this would be the answer.

like image 779
Thomas Washington Avatar asked Oct 29 '22 10:10

Thomas Washington


1 Answers

Please try the following in your view:

@model IEnumerable<DysonADPTest.UserViewModel.USerViewModelADP>

Your problem lies in using the .Select() method which changes the type your controller action is returning from

IEnumerable<DysonADPTest.Models.tblEmployeeADP>

which your view is also expecting to something entirely different. For this to work, the type your controller action returns and your view uses should match. It's either not use the .Select() method in your controller action or change the type your view uses.

like image 65
Patee Gutee Avatar answered Nov 15 '22 06:11

Patee Gutee