Entity Framework之DB First方式详解

 更新时间:2021年9月22日 10:03  点击:2000

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的两种更新方式。

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

[!--infotagslink--]

相关文章

  • PHP添加MongoDB扩展实例教程

    由于要使用mikoomi mongodb plugin插件,所以需要php对mongodb的扩展支持,默认通过源安装的php并没有mongodb的扩展支持,具体可以通过php -m|grep mongo 验证 。这里就结...2016-11-25
  • 安装使用Mongoose配合Node.js操作MongoDB的基础教程

    这篇文章主要介绍了安装使用Mongoose来让Node.js操作MongoDB的基础教程,前端js+后端node+js操作MongoDB正是所谓最流行的一种JavaScript全栈开发方案,需要的朋友可以参考下...2016-03-03
  • mongodb与mysql命令详细对比

    传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关...2013-09-11
  • 修复 Mac brew 安装 mongodb 报 Error: No available formula with the name ‘mongodb’ 问题详解

    最近在同事新的 Mac 电脑上安装 mongodb,报了错误 Error: No available formula with the name ‘mongodb’,今天就说说这个问题如何解决,需要的朋友可以参考下...2020-07-11
  • C#使用oledb导出数据到excel的方法

    这篇文章主要介绍了C#使用oledb导出数据到excel的方法,结合实例形式分析了C#操作oledb导出数据的相关技巧与注意事项,需要的朋友可以参考下...2020-06-25
  • Framework7 修改模态框默认文字(标题、确认|取消按钮、登录框提示)

    下面我们来看一篇关于Framework7 修改模态框默认文字(标题、确认|取消按钮、登录框提示) 的例子,希望这篇文章能够帮助到大家的哦。 Framework7 提供了许多常用的模...2016-10-02
  • Windows10安装MongoDB4.0详细步骤及启动配置教程

    这篇文章主要介绍了Windows10安装MongoDB4.0详细步骤及启动配置教程 ,本文通过图文并茂的形式给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • MongoDb CPU利用率过高问题如何解决

    这篇文章主要介绍了MongoDb CPU利用率过高问题如何解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-12-08
  • CentOS7.2 安装 MongoDB 3.4的教程

    这篇文章主要介绍了CentOS7.2 安装 MongoDB 3.4的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • NestJs使用Mongoose对MongoDB操作的方法

    这篇文章主要介绍了NestJs使用Mongoose对MongoDB操作的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-22
  • Windows Server 2012 R2或2016无法安装.NET Framework 3.5.1的解决方法

    这篇文章主要为大家详细介绍了Windows Server 2012 R2或2016无法安装.NET Framework 3.5.1,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-07-06
  • Zend Framework动作助手(Zend_Controller_Action_Helper)用法详解

    这篇文章主要介绍了Zend Framework动作助手(Zend_Controller_Action_Helper)用法,详细分析了动作助手Zend_Controller_Action_Helper功能,定义,使用方法与相关实现代码,需要的朋友可以参考下...2016-03-10
  • MongoDB CRUD操作中的插入实例教程

    这篇文章主要给大家介绍了关于MongoDB CRUD操作中的插入的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用MongoDB具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-12-08
  • Node+Express+MongoDB实现登录注册功能实例

    这篇文章主要介绍了Node+Express+MongoDB实现登录注册功能,需要的朋友可以参考下...2017-04-27
  • Navicat Premium连接mongodb详细教程

    这篇文章主要介绍了Navicat Premium连接mongodb详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-05
  • MongoDB操作符中的$elemMatch问题

    这篇文章主要介绍了MongoDB操作符中的$elemMatch问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • C#修改IIS站点framework版本号的方法

    这篇文章主要介绍了C#修改IIS站点framework版本号的方法,涉及C#调用使用ASP.NET IIS注册工具Aspnet_regiis.exe进行IIS站点framework版本号修改的方法,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • Zend Framework动作助手Redirector用法实例详解

    这篇文章主要介绍了Zend Framework动作助手Redirector用法,结合实例形式详细分析了转向器Redirector的功能,使用方法与相关注意事项,需要的朋友可以参考下...2016-03-10
  • MySQL的InnoDB引擎入门学习教程

    MySQL发展到今天,InnoDB引擎已经作为绝对的主力,除了像大数据量分析等比较特殊领域需求外,它适用于众多场景。然而,仍有不少开发者还在“执迷不悟”的使用MyISAM引擎,觉得对InnoDB无法把握好,还是MyISAM简单省事,还能支持快...2015-11-24
  • C#使用ODBC与OLEDB连接数据库的方法示例

    这篇文章主要介绍了C#使用ODBC与OLEDB连接数据库的方法,结合实例形式分析了C#基于ODBC与OLEDB实现数据库连接操作简单操作技巧,需要的朋友可以参考下...2020-06-25