我无法弄清楚这个错误发生了什么:
传递到字典中的模型项的类型为“System.Collections.Generic.List1 [RepositoryExample.Employee]”,但此字典需要“RepositoryExample.Models.IEmployeeManagerRepository”类型的模型项。
当我进入索引视图时,我收到错误。我从控制器添加了索引视图,但没有代码。我正在使用Linq to SQL。
@model RepositoryExample.Models.IEmployeeManagerRepository
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
这是我的代码:
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();
}
}
任何想法我做错了什么?我正在尝试按照本教程中的Repository模式示例:http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs。
答案 0 :(得分:15)
在Index.cshtml
视图顶部替换:
@model RepositoryExample.Models.IEmployeeManagerRepository
使用:
@model IEnumerable<RepositoryExample.Employee>
_repository.ListEmployees()
方法返回IEnumerable<Employee>
,这就是您在此处传递给视图的内容:
return View(_repository.ListEmployees());
这就是您应该在视图中的@model
指令中使用的类型。