Reputation: 83
I got this error
The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[CandidateScreening.Data.Entities.Patient]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable'1[CandidateScreening.Models.Patient]'.)
public ActionResult Index()
{
var Patient = _context.Patients.ToList();
return View(Patient);
}
@model IEnumerable<CandidateScreening.Models.Patient>
@{
ViewBag.Title = "index";
}
<h2>List Of the Patient</h2>
<table class="table">
<thead>
<tr>
<th>firstName</th>
<th>SurName</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td> @Html.ActionLink(item.Firstname, "Index", "detail")</td>
<td> @Html.ActionLink(item.Surname, "Index", "detail")</td>
<td> @Html.ActionLink(item.Gender, "Index", "detail")</td>
</tr>
}
</tbody>
</table>
could you tell me why I get this error?
I have try by changing IEnumerable
to List
but is not working yet
Upvotes: 0
Views: 456
Reputation: 24957
Assumed Patients
is an Entity Framework data context, ToList()
will generate list with object type set as IEnumerable<CandidateScreening.Data.Entities.Patient>
, which doesn't match with object type set by @model
directive (i.e. IEnumerable<CandidateScreening.Models.Patient>
).
To solve this issue, simply use Select()
LINQ query to project entity context into list of viewmodel class:
public ActionResult Index()
{
var Patient = _context.Patients.Select(x => new CandidateScreening.Models.Patient
{
// list of properties here
// example:
// PatientId = x.PatientId
}).ToList();
return View(Patient);
}
Or using query expression as alternative:
var Patient = (from patient in _context.Patients
select new CandidateScreening.Models.Patient
{
// list of properties here
// example:
// PatientId = patient.PatientId
}).ToList();
Upvotes: 1