部门和职员是1对多关系。用一个表格列出所有部门,并且在每行显示该部门下的所有职员名称。如下:
部门和职员的Model:
using System.Collections.Generic;namespace MvcApplication1.Models{ public class Department { public int Id { get; set; } public string Name { get; set; } public string Location { get; set; } public ListEmployees { get; set; } }}namespace MvcApplication1.Models{ public class Employee { public int Id { get; set; } public string Name { get; set; } public string Gender { get; set; } public int Salary { get; set; } public Department Department { get; set; } }}
需要一个Entity Framework的上下文,具体是派生于DbContext类:
using System.Data.Entity;namespace MvcApplication1.Models{ public class EmployeeDbContext : DbContext { public DbSetDepartments { get; set; } public DbSet Employees { get; set; } }}
using System.Collections.Generic;using System.Linq;using MvcApplication1.Models;namespace MvcApplication1.Repository{ public class EmployeeRepository { public ListGetDepartments() { using (EmployeeDbContext employeeDbContext = new EmployeeDbContext()) { return employeeDbContext.Departments.Include("Employees").ToList(); } } }}
EmployeeController中:
using System.Web.Mvc;using MvcApplication1.Repository;namespace MvcApplication1.Controllers{ public class EmployeeController : Controller { EmployeeRepository employeeRepository = new EmployeeRepository(); public ActionResult Index() { return View(employeeRepository.GetDepartments()); } }}
Employee/Index.cshtml强类型视图显示,使用由提供的一个漂亮表格样式呈现内容。
@model IEnumerable@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";} @if (Model.Count() > 0){ }else{ 暂无记录~~}
部门列表 @foreach (var item in Model) { 部门名称 地址 包含员工 } @item.Name @item.Location @{ Html.RenderPartial("Employees", @item.Employees);}
@model IEnumerable@if (Model.Count() > 0){ var result = string.Empty; foreach (var item in Model) { result += item.Name + ","; } @result.Substring(0, @result.Length -1)}else{ 该部门下暂无员工~~}
配置Web.config中的连接字符串,其中name属性值与派生于DbContext的EmployeeDbContext类名一致:
...
→运行,页面显示"暂无记录~~",因为数据库中还没数据。→打开Sql Server Management Studio,发现已经创建好了EFSample数据库以及表,插入一些数据。→再次运行,即可看到效果。
□ 参考资料