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

Entity Framework之DB First方式的更多相关文章

  1. 关于Entity Framework采用DB First模式创建后的实体批量修改相关属性技巧

    Entity Framework采用DB First模式创建实体是比较容易与方便的,修改已创建的实体在个数不多的情况下也是没问题的,但如果已创建的实体比较多,比如10个实体以上,涉及修改的地方比较多的 ...

  2. Entity Framework入门教程: Entity Framework支持的查询方式

    Entity Framework支持的查询方式有三种 LINQ to Entities Entity SQL Native SQL [LINQ to Entities] LINQ(语言集成查询)是从V ...

  3. Entity Framework常用的查询方式

    Entity Framework支持的查询方式有三种 LINQ to Entities Entity SQL Native SQL [LINQ to Entities] LINQ(语言集成查询)是从V ...

  4. [EF] 如何在 Entity Framework 中以手动方式设定 Code First 的 Migration 作业

    Entity Framework (简称 EF) 发展到现在, 版本已经进入 6.1.0, 距离我写的「在 VS2013 以 Code First 方式建立 EF 资料库」这篇文章已有半年的时间.如果 ...

  5. Oracle中使用Entity Framework 6.x Code-First方式开发

    去年写过一篇EF的简单学习笔记,当时EF还不支持Oracle的Code-First开发模式,今天无意又看了下Oracle官网,发现EF6.X已经支持了,并且给出了二篇教程(英文版): 1.Using ...

  6. Entity Framework后台采用分页方式取数据与AspNetPager控件的使用

    本文是一个对AspNetPager控件使用的笔记! 有关AspNetPager控件可以查看杨涛主页.这是一个开放的自定义ASP.NET控件,支持各种自定义的数据分页方式,使用很方便,而且功能也很强大, ...

  7. Entity Framework CodeFirst------使用CodeFirst方式建立数据库连接(一)

    本文分步演练介绍通过 Code First 开发建立新数据库.这个方案包括建立不存在的数据库(Code First 创建)或者空数据库(Code First 向它添加新表).借助 Code First ...

  8. 如何使用ASP.NET Web API OData在Oracle中使用Entity Framework 6.x Code-First方式开发 OData V4 Service

    环境: Visual Studio 2013 + .Net Framework 4.5.2 1.新建项目 2.安装OData,ODP.NET 安装的包: 下面是部分代码: using System; ...

  9. 使用Entity Framework通过code first方式创建数据库和数据表

    开发环境 WIN10 Entity Framework6.0  MVC5.0  开发工具 VS2015  SqlServer2012 1.创建上下文Context继承DbContext,并创建其他的业 ...

随机推荐

  1. udgrade rubygems-update

    gem install rubygems-update update_rubygems gem update --system gem install rubygems-bundler  

  2. react config test env with jest and create-react-app 1

    /.babelrc { "presets": ["@babel/preset-env","@babel/preset-react"], &q ...

  3. Impala查询详解

    Impala的定位是一种新型的MPP查询引擎,但是它又不是典型的MPP类型的SQL引擎,提到MPP数据库首先想到的可能是GreenPlum,它的每一个节点完全独立,节点直接不共享数据,节点之间的信息传 ...

  4. HTML引入CSS样式的四种方法

    在HTML中引入CSS的方法主要有四种,它们分别是行内式.内嵌式.链接式和导入式. 1.行内式          行内式是在标记的style属性中设定CSS样式.这种方式没有体现出CSS的优势,不推荐 ...

  5. 一个基于Socket的http请求监听程序实现

    首先来看以下我们的需求: 用java编写一个监听程序,监听指定的端口,通过浏览器如http://localhost:7777来访问时,可以把请求到的内容记录下来,记录可以存文件,sqlit,mysql ...

  6. ruby on rails 权限管理gem cancan

    系统的model关系如下: 用户类 class AdminUser embeds_many :permissions  accepts_nested_attributes_for :permissio ...

  7. Python解析xml与JSON

    xml与json是常用的文件交换格式,常用来表示网页的html则是xml的变种.解析xml和json在web开发中有着重要应用. DOM解析XML 文件对象模型(Document Object Mod ...

  8. Prim算法和Kruskal算法求最小生成树

    Prim算法 连通分量是指图的一个子图,子图中任意两个顶点之间都是可达的.最小生成树是连通图的一个连通分量,且所有边的权值和最小. 最小生成树中,一个顶点最多与两个顶点邻接:若连通图有n个顶点,则最小 ...

  9. 单击GridView进入编辑模式

    一直以来,Insus.NET在实现GridView编辑时,均是在每笔记录第一列或是最后一列放置编辑铵钮,点击编辑铵钮之后,进行编辑模式.本博文是使用另外方式,即是点击GridView记录行任一位置,进 ...

  10. ADO五大对象(转载)

    来源:http://blog.csdn.net/u013201439/article/details/51111969 ADO五大对象(转载) 一.绪论 1.引言 在数据库应用系统中,必定要涉及到对数 ...