ASP.Net MVC+Entity Framework 的架构案例
Entity Framework Code First
Fluent API - 配置关系
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolService.Entities { public abstract class EntityBase { public int Id { get; set; } public DateTime CreateDateTime { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolService.Entities { public class Student : EntityBase { public string Name { get; set; } public int Age { get; set; } public int MinZuId { get; set; } public MinZu MinZu { get; set; } public int ClassId { get; set; } public Class Class { get; set; } } }
using SchoolService.Entities; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolService.EntityConfig { public class StudentConfig:EntityTypeConfiguration<Student> { public StudentConfig() { ToTable("T_Students"); Property(s => s.Name).IsRequired(); HasRequired(s => s.MinZu).WithMany().HasForeignKey(s=>s.MinZuId); HasRequired(s => s.Class).WithMany().HasForeignKey(s => s.ClassId); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SchoolService.Entities { public class EntityContext:DbContext { public EntityContext():base("name=connStr") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); } public DbSet<MinZu> MinZus { get; set; } public DbSet<Class> Classes{ get; set; } public DbSet<Student> Students { get; set; } } }
using schoolDTO; using SchoolService.Entities; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolService { public class StudentService { public void Add(string name, int age, int minZuId, int classId) { using (EntityContext ctx = new EntityContext()) { Student student = new Student { Name = name, Age = age, MinZuId = minZuId, ClassId = classId,CreateDateTime=DateTime.Now }; ctx.Students.Add(student); ctx.SaveChanges(); } } public void Delete(int id) { using (EntityContext ctx = new EntityContext()) { Student student = ctx.Students.SingleOrDefault(s => s.Id == id); if (student == null) { throw new ArgumentException("获取不到学生信息"); } ctx.Students.Remove(student); //Student student = new Student { Id = id }; //ctx.Entry(student).State = EntityState.Deleted; ctx.SaveChanges(); } } public void Update(int id, string name, int age, int minZuId, int classId) { using (EntityContext ctx = new EntityContext()) { Student student = ctx.Students.SingleOrDefault(s => s.Id == id); student.Name = name; student.Age = age; student.MinZuId = minZuId; student.ClassId = classId; ctx.Entry(student).State = EntityState.Modified; ctx.SaveChanges(); } } private StudentDTO ToDTO(Student student) { StudentDTO dto = new StudentDTO(); dto.Id = student.Id; dto.Name = student.Name; dto.Age = student.Age; dto.ClassId = student.ClassId; dto.ClassName = student.Class.Name; dto.MinZuId = student.MinZuId; dto.MinZuName = student.MinZu.Name; dto.CreateDateTime = student.CreateDateTime; return dto; } public IEnumerable<StudentDTO> CetAll() { using (EntityContext ctx = new EntityContext()) { var students = ctx.Students.AsNoTracking().Include("MinZu").Include("Class"); foreach (Student student in students) { yield return ToDTO(student); } } } public IEnumerable<StudentDTO> CetByClassId(int classId) { using (EntityContext ctx = new EntityContext()) { var students = ctx.Students.AsNoTracking().Include("MinZu").Include("Class").Where(s => s.ClassId == classId); foreach (Student student in students) { yield return ToDTO(student); } } } public StudentDTO CetById(int id) { using (EntityContext ctx = new EntityContext()) { var student = ctx.Students.AsNoTracking().Include("MinZu").Include("Class").SingleOrDefault(s => s.Id == id); if (student == null) { return null; } return ToDTO(student); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace schoolDTO { public class StudentDTO { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public int MinZuId { get; set; } public string MinZuName { get; set; } public int ClassId { get; set; } public string ClassName { get; set; } public DateTime CreateDateTime { get; set; } } }
using schoolDTO; using SchoolService; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SchoolWeb.Controllers { public class DefaultController : Controller { // GET: Default public ActionResult Index() { StudentService service = new StudentService(); IEnumerable<StudentDTO> list = service.CetAll(); return View(list); } public ActionResult Delete(int id) { StudentService service = new StudentService(); service.Delete(id); return RedirectToAction("Index"); } } }
@model IEnumerable<StudentDTO> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>学生列表</title> </head> <body> <a href="/Student/AddNew/">新增</a> <table border="1" cellpadding="5" cellspacing="0" width="500"> <tr> <th>姓名</th> <th>年龄</th> <th>班级</th> <th>民族</th> <th>修改</th> <th>删除</th> </tr> @foreach (StudentDTO student in Model) { <tr> <td>@student.Name</td> <td>@student.Age</td> <td>@student.ClassName</td> <td>@student.MinZuName</td> <td><a href="/Student/Update/@(student.Id)">修改</a></td> <td><a href="/Default/Delete/@(student.Id)" onclick="return confirm('确定要删除吗?')">删除</a></td> </tr> } </table> </body> </html>
using schoolDTO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SchoolWeb.Models { public class StudentViewModel { public StudentDTO Student { get; set; } public SelectList MinZus { get; set; } public SelectList Classes { get; set; } } }
using schoolDTO; using SchoolService; using SchoolWeb.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SchoolWeb.Controllers { public class StudentController : Controller { // GET: Student [HttpGet] public ActionResult AddNew() { SelectList minzus = new SelectList(new MinZuService().GetAll(),"Id","Name"); SelectList classes = new SelectList(new ClassService().GetAll(), "Id", "Name"); StudentViewModel model = new StudentViewModel(); model.MinZus = minzus; model.Classes = classes; return View(model); } [HttpPost] public ActionResult AddNew(string name,int age,int mingzuSelect,int classSelect) { StudentService service = new StudentService(); service.Add( name, age, mingzuSelect, classSelect); return Redirect("~/Default/"); } [HttpGet] public ActionResult Update(int id) { StudentDTO dto = new StudentService().CetById(id); if (dto==null) { //错误提示 return Content("获取不到学生信息!"); } SelectList minzus = new SelectList(new MinZuService().GetAll(), "Id", "Name", dto.MinZuId); SelectList classes = new SelectList(new ClassService().GetAll(), "Id", "Name",dto.ClassId); StudentViewModel model = new StudentViewModel(); model.MinZus = minzus; model.Classes = classes; model.Student = dto; return View(model); } [HttpPost] public ActionResult Update(int id,string name, int age, int mingzuSelect, int classSelect) { StudentService service = new StudentService(); service.Update(id,name, age, mingzuSelect, classSelect); return Redirect("~/Default/"); } } }
@model StudentViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>修改</title> <style type="text/css"> div { padding:5px; } </style> </head> <body> <form action="/Student/Update/" method="post"> <input type="hidden" name="id" value="@Model.Student.Id" /> <div> 姓名:<input type="text" name="name" value="@Model.Student.Name" /> </div> <div> 年龄:<input type="text" name="age" value="@Model.Student.Age" /> </div> <div> 民族:@Html.DropDownList("mingzuSelect", Model.MinZus) </div> <div> 班级:@Html.DropDownList("classSelect", Model.Classes) </div> <div> <input type="submit" value=" 修 改 " /> </div> </form> </body> </html>