0

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

Tima mehro
  • 73
  • 1
  • 8
  • 3
    You appear to have defined `Patient` in 2 separate assemblies - `CandidateScreening.Data.Entities` and `CandidateScreening.Models` - they are not the same –  Oct 18 '18 at 07:32
  • 2
    Possible duplicate of [The model item passed into the dictionary is of type .. but this dictionary requires a model item of type](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ) –  Oct 18 '18 at 07:33
  • 1
    use the automapper (https://automapper.org/) to map your entities to the CandidateScreening.Models.Patient – Kalyan Oct 19 '18 at 01:46

1 Answers1

1

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();
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61