【发布时间】:2021-03-01 23:54:27
【问题描述】:
我使用 N-Layer Architech 和依赖注入。 我还想在员工列表中列出部门列表。
public List<Employee> ListEmployee()
{
using (var context = new DatabaseContext())
{
return context.Set<Employee>().Include("Department").ToList();
}
}
或者我尝试了两种方法但得到了同样的错误。
public IQueryable<Employee> GetQueryableEmployee()
{
using (var context = new DatabaseContext())
{
return context.Set<Employee>().Include("Department").AsQueryable<Employee>();
}
}
我像这样创建了我的表。 部门表
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
和员工表
public ICollection<Employee> Employees { get; set; }
我使用 Fluent Api 创建的一对多关系
modelBuilder.Entity<Employee>()
.HasRequired<Department>(e => e.Department)
.WithMany(c => c.Employees)
.HasForeignKey<int>(e => e.DepartmentID);
员工控制器
public class EmployeeController : Controller
{
private readonly IEmployeeService _employeeService;
public EmployeeController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
public ActionResult Index()
{
var employee = _employeeService.ListEmployee();
return View(employee);
}
和查看
@model IEnumerable<Test.Entities.Concreate.Employee>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Department.DepartmentName)
</td>
如何在同一个列表中显示两个表? 我认为需要平衡 DepartmentID 的地方
【问题讨论】:
-
Fior
GetQueryableEmployee你会有这个例外。因为您已经处理了已生成IQueryable的上下文 -
var employee=_employeeService.GetQueryableEmployee 是这样吗?
-
是的,这种用法是错误的。您不必每次都创建上下文,而是配置 DI,以便为每个请求创建实例。
-
builder.RegisterType
().As (); builder.RegisterType ().As (); -
我是这样做的。如何配置 DI?
标签: c# asp.net-mvc entity-framework linq dependency-injection