侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Entity Framework之DB First方式详解

数据库  /  管理员 发布于 5年前   349

EF(Entity Framework的简称,下同)有三种方式,分别是:DataBase First、 Model First和Code First。

下面是Db First的方式:

1. 数据库库中存在两个表,一个是专业表,一个学生表,一个学生只能属于一个专业:

其中T_Major是专业表,T_Student是学生表,StudentId是学号,MajorId是专业Id,T_Major与T_Student是一对多的关系。

2. 项目中添加数据库实体模型

因为之前没有配置过数据库连接,所以点击“新建库连接”,如果之前配置过数据库连接,可以直接从下拉列表中选择或者新建

选择需要生成的表/存储过程等

点击“完成”

这里会弹出如下图的窗口,然后选择确定(如果再弹出,也选择确定),如果不小心点击了取消,可以在模型设计界面Ctrl + S(保存的快捷键),或如下图的操作,然后会弹出窗口,一直确定就行。

这里是使用MVC,所以添加一个控制器来测试(这里为了快速生成读写的控制器方法,选择“包含读/写操作的MVC5控制器”)

生成代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Zhong.Web.Controllers{  public class StudentController : Controller  {    // GET: Student    public ActionResult Index()    {      return View();    }    // GET: Student/Details/5    public ActionResult Details(int id)    {      return View();    }    // GET: Student/Create    public ActionResult Create()    {      return View();    }    // POST: Student/Create    [HttpPost]    public ActionResult Create(FormCollection collection)    {      try      {        // TODO: Add insert logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }    // GET: Student/Edit/5    public ActionResult Edit(int id)    {      return View();    }    // POST: Student/Edit/5    [HttpPost]    public ActionResult Edit(int id, FormCollection collection)    {      try      {        // TODO: Add update logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }    // GET: Student/Delete/5    public ActionResult Delete(int id)    {      return View();    }    // POST: Student/Delete/5    [HttpPost]    public ActionResult Delete(int id, FormCollection collection)    {      try      {        // TODO: Add delete logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }  }}

同样的方法添加一个Major控制器

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Zhong.Web.Controllers{  public class MajorController : Controller  {    // GET: Major    public ActionResult Index()    {      return View();    }    // GET: Major/Details/5    public ActionResult Details(int id)    {      return View();    }    // GET: Major/Create    public ActionResult Create()    {      return View();    }    // POST: Major/Create    [HttpPost]    public ActionResult Create(FormCollection collection)    {      try      {        // TODO: Add insert logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }    // GET: Major/Edit/5    public ActionResult Edit(int id)    {      return View();    }    // POST: Major/Edit/5    [HttpPost]    public ActionResult Edit(int id, FormCollection collection)    {      try      {        // TODO: Add update logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }    // GET: Major/Delete/5    public ActionResult Delete(int id)    {      return View();    }    // POST: Major/Delete/5    [HttpPost]    public ActionResult Delete(int id, FormCollection collection)    {      try      {        // TODO: Add delete logic here        return RedirectToAction("Index");      }      catch      {        return View();      }    }  }}

由于学生表MajorId依赖于Major表,所以需要先有专业,才能新增学生数据(这里不讨论是否合理)

编写逻辑代码,创建视图

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Zhong.Web.Models;namespace Zhong.Web.Controllers{  public class MajorController : Controller  {    // GET: Major    public ActionResult Index()    {      var majors = new EFDbEntities().T_Major.ToList();      return View(majors);    }    // GET: Major/Details/5    public ActionResult Details(int id)    {      var major = new EFDbEntities().T_Major.Find(id);      if (major == null)      {        return Content("参数错误");      }      return View(major);    }    // GET: Major/Create    public ActionResult Create()    {      return View();    }    // POST: Major/Create    [HttpPost]    public ActionResult Create(T_Major entity)    {      if (entity != null)      {        var entities = new EFDbEntities();        entities.T_Major.Add(entity);        entities.SaveChanges();      }      return RedirectToAction("Index");    }    // GET: Major/Edit/5    public ActionResult Edit(int id)    {      var entity = new EFDbEntities().T_Major.Find(id);      if (entity == null)      {        return Content("参数错误");      }      return View(entity);    }    // POST: Major/Edit/5    [HttpPost]    public ActionResult Edit(T_Major entity)    {      if (entity == null)      {        return Content("参数错误");      }      var entities = new EFDbEntities();      #region 方式一       ////该方式一般是根据主键先读取数据,然后再逐个赋值,最后更新      //var oldEntity = entities.T_Major.Find(entity.Id);      //if (oldEntity!=null)      //{      //  oldEntity.Name = entity.Name;      //  entities.SaveChanges();      //}      #endregion      #region 方式二      //该方式是直接将新的实体(可能是new出来的并且对主键等的属性赋值好了)附加到上下文,然后标记状态为修改Modified      entities.T_Major.Attach(entity);      entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;      entities.SaveChanges();      #endregion      return RedirectToAction("Index");    }    // GET: Major/Delete/5    public ActionResult Delete(int id)    {      var major = new EFDbEntities().T_Major.Find(id);      return View(major);    }    // POST: Major/Delete/5    [HttpPost]    public ActionResult Delete(int id, FormCollection collection)    {      try      {        // TODO: Add delete logic here        var entities = new EFDbEntities();        var major = entities.T_Major.Find(id);        entities.T_Major.Remove(major);        entities.SaveChanges();        return RedirectToAction("Index");      }      catch      {        return View();      }    }  }}

添加专业:

专业列表:

同样实现学生控制器与视图:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Zhong.Web.Models;namespace Zhong.Web.Controllers{  public class StudentController : Controller  {    private EFDbEntities entities = new EFDbEntities();    // GET: Student    public ActionResult Index()    {      var students = entities.T_Student.ToList();      return View(students);    }    // GET: Student/Details/5    public ActionResult Details(int id)    {      var student = entities.T_Student.Find(id);      return View(student);    }    // GET: Student/Create    public ActionResult Create()    {      ViewData["MajorId"] = entities.T_Major.Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() });      return View();    }    // POST: Student/Create    [HttpPost]    public ActionResult Create(T_Student entity)    {      entities.T_Student.Add(entity);      entities.SaveChanges();      return RedirectToAction("Index");    }    // GET: Student/Edit/5    public ActionResult Edit(int id)    {      var student = entities.T_Student.Find(id);      ViewData["MajorId"] = entities.T_Major.Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() });      return View(student);    }    // POST: Student/Edit/5    [HttpPost]    public ActionResult Edit(T_Student entity)    {      if (entity == null)      {        return Content("参数错误");      }      entities.T_Student.Attach(entity);      entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;      entities.SaveChanges();      return RedirectToAction("Index");    }    // GET: Student/Delete/5    public ActionResult Delete(int id)    {      var student = entities.T_Student.Find(id);      return View(student);    }    // POST: Student/Delete/5    [HttpPost]    public ActionResult Delete(int id, FormCollection collection)    {      var student = entities.T_Student.Find(id);      entities.T_Student.Remove(student);      entities.SaveChanges();      return RedirectToAction("Index");    }  }}

添加学生时,报错如下:

于是在控制器中增加如下代码:

刷新页面:

编辑:

删除:

列表:

在MajorController中有介绍EF的两种更新方式。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    MongoDB.Net工具库MongoRepository使用方法详解
    下一条:
    Visual Studio(VS2017)配置C/C++ PostgreSQL9.6.3开发环境
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客