Return specific columns from an Entityy Framework query using MVC

I am new to using both Entity Framework and MVC, but not new to programming. I work with a large table and I want to return the selected query columns back to the view and list them. The main request 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 C # base class for strong input of results (i.e. UserViewModel ) and I still get the error message:

The model element passed to the dictionary is of the type 'System.Collections.Generic.List1 [UserViewModel.USerViewMode YEARS]', but this element requires a model element of the type 'System.Collections.Generic.IEnumerable1 [DysonADPTest.Models.tblEmployeeADP]'.

when I execute the page.

I'm not sure that I went missing as I was sure (soaking what Ive read) that this would be the answer.

+5
source share
2 answers

Try the following on your screen:

 @model IEnumerable<DysonADPTest.UserViewModel.USerViewModelADP> 

Your problem is using the .Select () method, which changes the type of controller action you are returning from

 IEnumerable<DysonADPTest.Models.tblEmployeeADP> 

which your look also expects something completely different. For this to work, the type that returns the action of your controller and your use in the view must match. It either does not use the .Select () method in the action of your controller, or changes the type of view you are using.

+2
source

You create a list with a new object type ( USerViewMode‌​lADP )

You can filter, but just keep the same type (objects)

 public ActionResult Index() { var tblEmployeeADPs = db.tblEmployeeADPs .Where(p => p.Status == "Active") .Select(p => p) return View(tblEmployeeADPs.ToList()); } 
0
source

Source: https://habr.com/ru/post/1265788/


All Articles