I can't figure out what's going on with this error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[RepositoryExample.Employee]', but this dictionary requires a model item of type 'RepositoryExample.Models.IEmployeeManagerRepository'.`
I get the error when I go to the Index view. I added the Index View from the controller but there is no code in it. I'm using Linq to SQL.
@model RepositoryExample.Models.IEmployeeManagerRepository
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
This is my code:
EmployeeController.cs
// GET: /Employee/
public ActionResult Index()
{
return View(_repository.ListEmployees());
}
LinqEmployeeManagerRepository.cs
public class LinqEmployeeManagerRepository: RepositoryExample.Models.IEmployeeManagerRepository
{
private DeptDirectoryDataClassesDataContext _db = new DeptDirectoryDataClassesDataContext();
public Employee GetEmployee(string UserName)
{
return (from e in _db.Employees where e.UserName == UserName select e).FirstOrDefault();
}
public IEnumerable<Employee> ListEmployees()
{
return _db.Employees.ToList();
}
public Employee CreateEmployee(Employee employeeToCreate)
{
_db.Employees.InsertOnSubmit(employeeToCreate);
_db.SubmitChanges();
return employeeToCreate;
}
public Employee EditEmployee(Employee employeeToEdit)
{
var OriginalEmployee = GetEmployee(employeeToEdit.UserName);
_db.Employees.Attach(employeeToEdit, OriginalEmployee);
_db.SubmitChanges();
return employeeToEdit;
}
public void DeleteEmployee(Employee employeeToDelete)
{
var OriginalEmployee = GetEmployee(employeeToDelete.UserName);
_db.Employees.DeleteOnSubmit(OriginalEmployee);
_db.SubmitChanges();
}
}
IEmployeeManagerRepository.cs
namespace RepositoryExample.Models
{
public interface IEmployeeManagerRepository
{
Employee CreateEmployee(Employee employeeToCreate);
void DeleteEmployee(Employee employeeToDelete);
Employee EditEmployee(Employee employeeToUpdate);
Employee GetEmployee(string UserName);
IEnumerable<Employee> ListEmployees();
}
}
Any ideas what I'm doing wrong? I'm trying to follow the example on Repository pattern in this tutorial: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs.
In the top of your Index.cshtml
view replace:
@model RepositoryExample.Models.IEmployeeManagerRepository
with:
@model IEnumerable<RepositoryExample.Employee>
The _repository.ListEmployees()
method returns IEnumerable<Employee>
and that's what you are passing to the view here:
return View(_repository.ListEmployees());
So that's the type you should be using in the @model
directive in your view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With