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 { getset; }
        public DateTime CreateDateTime { getset; }
    }
}

 

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 { getset; }
        public int Age { getset; }
        public int MinZuId { getset; }
        public MinZu MinZu { getset; }
        public int ClassId { getset; }
        public Class Class { getset; }
    }
}

 

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 { getset; } 
        public DbSet<Class> Classes{ getset; } 
        public DbSet<Student> Students { getset; } 
    }
}

 

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 { getset; }
        public string Name { getset; }
        public int Age { getset; }
        public int MinZuId { getset; }
        public string MinZuName { getset; }
        public int ClassId { getset; }
        public string ClassName { getset; }
        public DateTime CreateDateTime { getset; }
    }
}

 

 

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>
    <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><href="/Student/Update/@(student.Id)">修改</a></td>
                <td><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 { getset; }
        public SelectList MinZus { getset; }
        public SelectList Classes { getset; }
    }
}

 

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>

 

转载于:https://www.cnblogs.com/linyongqin/articles/7154655.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值