热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

EntityFramework之DBFirst方式详解

这篇文章主要为大家详细介绍了EntityFramework三种方式之一DataBaseFirst,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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


推荐阅读
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文介绍了使用postman进行接口测试的方法,以测试用户管理模块为例。首先需要下载并安装postman,然后创建基本的请求并填写用户名密码进行登录测试。接下来可以进行用户查询和新增的测试。在新增时,可以进行异常测试,包括用户名超长和输入特殊字符的情况。通过测试发现后台没有对参数长度和特殊字符进行检查和过滤。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • ASP.NET2.0数据教程之十四:使用FormView的模板
    本文介绍了在ASP.NET 2.0中使用FormView控件来实现自定义的显示外观,与GridView和DetailsView不同,FormView使用模板来呈现,可以实现不规则的外观呈现。同时还介绍了TemplateField的用法和FormView与DetailsView的区别。 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
  • MVC设计模式的介绍和演化过程
    本文介绍了MVC设计模式的基本概念和原理,以及在实际项目中的演化过程。通过分离视图、模型和控制器,实现了代码的解耦和重用,提高了项目的可维护性和可扩展性。详细讲解了分离视图、分离模型和分离控制器的具体步骤和规则,以及它们在项目中的应用。同时,还介绍了基础模型的封装和控制器的命名规则。该文章适合对MVC设计模式感兴趣的读者阅读和学习。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文讨论了如何在不使用SearchBar display controller的情况下,单独使用SearchBar并捕获其textChange事件。作者介绍了实际状况,即左侧SliderMenu中的SearchBar需要在主页TableView中显示搜索结果。然后,作者提供了解决方案和步骤,帮助读者实现这一功能。 ... [详细]
author-avatar
yushun
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有