Asp.Net核心EF核心表联接

时间:2019-11-18 08:18:52

标签: c# asp.net-mvc asp.net-core entity-framework-core

我有两个对象,让我们说雇员和地址如下

public class Employee
 {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public int DepartmentId {get; set; }
}

public class Department
{
        public int Id { get; set; }
        public string Name { get; set; }
}

这种关系模型是每个员工都属于一个部门(使用DepartmentID属性)

我想创建一个显示所有员工的视图,而不是显示部门ID,而是显示部门名称

我的控制器看起来像这样

  

公共类EmployeeController:控制器       {           私有只读IAppRepository _appRepository;

    public EmployeeController(IAppRepository appRepository)
    {
        _appRepository = appRepository;
    }
     

公共ViewResult列表           {

        Department department;

        // retrieve all employee from DBContext (SQL Server)
        var model = _appRepository.GetEmployees;

        // retrieve department details
        department = _appRepository.GetDepartment(model.DepartmentId);
        ViewBag.department = department;
      } 
     

}

我的问题似乎出在最后两行(//检索部门详细信息。因为模型返回了一个可枚举的雇员。

这是怎么实现的,我当时在考虑使用ViewModel,但还没有找到方法。谢谢

1 个答案:

答案 0 :(得分:0)

我认为,您可以配置EmployeeDepartment之间的关系,请参考here

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public int DepartmentId { get; set; }

    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
}

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
}

在您的存储库GetEmployees中,您可以使用Department使所有员工拥有自己的Include,请参阅here

var employees = _context.Employees.Include(e => e.Department).ToList();

然后您的model中的var model = _appRepository.GetEmployees;将包含每位员工的部门信息,您可以在视图中获得姓名,例如

@model IEnumerable<Employee>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Department)
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Department.Name)
            </td>
        </tr>
}
    </tbody>
</table>
相关问题