【转】MVC中code first方式开发,数据库的生成与更新(Ef6)
一,在models文件夹中,建立相应的model文件
这里注意一点,这里建立的class名,就是数据库里表的名字。
在这里面,可以建立表之间的关系。
这里要说明一点的事,一般情况下,我们会把n:m的形式,变成两个1:n的模式
//学生信息
namespace codefirst.Models
{
public class Students
{
public int ID { get; set; } [Required]
[MaxLength(10)]
public string stu_Name { get; set; } public string stu_Pwd { get; set; } public string stu_sex { get; set; } public int stu_age { get; set; } public virtual ICollection<StuCousers> StuCousers { get; set; }
}
} //课程信息
namespace codefirst.Models
{
public class Courses
{
public int ID { get; set; } public string course_Name { get; set; } public string course_code { get; set; } public virtual ICollection<StuCousers> StuCousers { get; set; }
}
} //学生课程关联表
namespace codefirst.Models
{
public class StuCousers
{
public int ID { get; set; } public int StudentID { get; set; } public int CourseID { get; set; } public virtual Students Student { get; set; } public virtual Courses Course { get; set; }
}
}
二,新建一个Dal文件夹,用来建立Database Context
namespace codefirst.DAL
{
public class BaseContext : DbContext
{ /// <summary>
/// 构造函数中的 base("AccountContext") 。
/// 默认情况下和类名一样,即AccountContext,我们显式的给他指定出来。
/// </summary>
public BaseContext()
: base("BaseContext")
{ } public DbSet<Students> Students { get; set; } public DbSet<Courses> Courses { get; set; } public DbSet<StuCousers> StuCousers { get; set; } /// <summary>
/// 指定单数形式的表名
/// 默认情况下会生成复数形式的表,如SysUsers
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
这里面DbSet对应着数据库里表
三,初始化数据库与表
第一次运行程序时新建数据库,插入测试数据; model改变(和database不一致)时删除重建数据库,插入测试数据。
先不用管数据丢失的问题,直接drop and re-create比较方便。
namespace codefirst.DAL
{
public class BaseInitializer : DropCreateDatabaseIfModelChanges<BaseContext>
{
protected override void Seed(BaseContext context)
{
var stu = new List<Students>
{
new Students{stu_Name="小明",stu_Pwd="123456",stu_sex="男"},
new Students{stu_Name="小芳",stu_Pwd="654321",stu_sex="女"}
}; stu.ForEach(s => context.Students.Add(s));
context.SaveChanges(); var cou = new List<Courses>
{
new Courses{course_Name="语文",course_code="10001"},
new Courses{course_Name="数学",course_code="10002"}
}; cou.ForEach(c => context.Courses.Add(c));
context.SaveChanges();
}
}
}
四,修改根目录下面的Web.config文件,添加
<connectionStrings>
<add name="BaseContext" connectionString="Data Source=.;database=StuAndCourse;uid=sa;pwd=xxxxxxx;AttachDBFilename=|DataDirectory|\StuAndCourse.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
这样,会在App_Data文件夹下生成名为StuAndCourse的数据库
五,在Global.asax文件,添加创建语句
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes); //添加建表
Database.SetInitializer<BaseContext>(new BaseInitializer());
}
六,建立Controllers文件,向前台输出数据
namespace codefirst.Controllers public class StudentController : Controller
{ BaseContext db = new BaseContext(); // GET: Student
public ActionResult Index()
{
return View(db.Students.ToList());
}
}
七,建立Views文件,用来显示数据
@model IEnumerable<codefirst.Models.Students>
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.stu_Name)
</td>
<td>
@foreach(var sc in item.StuCousers)
{
@Html.Label(sc.Course.course_Name)
}
</td>
</tr>
}
</table>
</div>
</body>
</html>
好,现在运行程序,你会发现,数据显示出来了,而且数据库也建立成功了。这里为什么要有第六,七步呢,因为你要有一个操作数据库的代码,它才会去建数据库。
下面我们再来看一下,如果我修改了Models中的文件,使得SysUser与数据库中的SysUser表的字段不一样了,这样如果我再运行程序,你会发现数据库被重置了。
这为什么呢,还记得第三步吗,这里就是如果结构不一定,就会删除再生成表。
可是我们在开始的过程中,有一些数据,不希望丢怎么办呢。
工具 -> 库程序包管理器 -> 程序包管理器控制台
运行命令 Enable-Migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded
migration '201212090821166_InitialCreate' corresponding to existing
database. To use an automatic migration instead, delete the Migrations
folder and re-run Enable-Migrations specifying the
-EnableAutomaticMigrations
parameter.
会出现,上面这个错误。不用管它,这时候,你会发现在程序端多出一个文件夹叫Migrations
这里面有一个Configuration.cs文件
打开它,然后修改成如下样子,
public Configuration()
{
AutomaticMigrationsEnabled = true; //这里变成true
ContextKey = "codefirst.DAL.BaseContext";
}
修改完成后,运行
Update-Database -Force这个时候,你再看一下数据库里面的表结构是不是变了,而数据却没有丢呢.
以后再有更改,只要保证Configuration.cs文件中的AutomaticMigrationsEnabled = true;
只运行Update-Database -Force就可以了
转自:https://blog.csdn.net/chenguang79/article/details/50847550
【转】MVC中code first方式开发,数据库的生成与更新(Ef6)的更多相关文章
- MVC中code first方式开发,数据库的生成与更新
在使用EF的实际编程中我们经常遇到这样的问题:发现实体结构需要新增加一个字段,或者减少一个字段,急需把实体结构修改,并让数据库更新这种修改.在用Model First或者Database First的 ...
- 在ASP.NET MVC中以post方式传递数组参数的示例
最近在工作中用到了在ASP.NET MVC中以post方式传递数组参数的情况,记录下来,以供参考. 一.准备参数对象 在本例中,我会传递两个数组参数:一个字符串数组,一个自定义对象数组.这个自定义对象 ...
- Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法
Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法 在Action中方法的返回值都是字符串行,一般情况是返回某个JSP,如: return "xx" ...
- 在ASP.NET MVC中以post方式传递数组参数的示例【转】
最近在工作中用到了在ASP.NET MVC中以post方式传递数组参数的情况,记录下来,以供参考. 一.准备参数对象 在本例中,我会传递两个数组参数:一个字符串数组,一个自定义对象数组.这个自定义对象 ...
- IOC容器-Autofac在MVC中实现json方式注入使用
在你阅读时,默认已经了解IOC和autofac的基本用法, 我在最近的我的博客项目中运用了IOC autofac 实现了依赖注入 由于我的项目时asp.net MVC所以我目前向大家展示MVC中如何使 ...
- ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(二)
由于大家都热衷于对ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(一)的浏览下面我分享下我的源文件git仓库: 用法(这边我是对缓存的一些操作不需要可以省去):https://github.c ...
- MVC中使用JQuery方式进行异步请求和使用自带方式进行异步请求
在MCV中使用异步请求可以很很高效地进行前台和后台的数据传递,在这里,笔者为初学者介绍两种在MVC中常用的异步请求处理方式. 在这里,我们通过在一个页面中放置一个按钮来异步获取当前服务器端的系统时间为 ...
- MVC中关于Membership类跟数据库的问题
Membership它们用的是ASPNETDB这个数据库,但我们可以使用我们自定义的数据库,然而除非我们自定义的数据库有着跟这个ASPNETDB一样的模式,否则ASP.NET提供的默认的SqlMemb ...
- MVC中页面传值方式总结
MVC中的页面传值,通常指Controller和view之间的数据传递,经常用到的有几种方式,总结如下: 一.Controller----------->View(控制器传到视图) 1.View ...
随机推荐
- Echarts 地图上显示数值
Echarts 地图上展示数值,效果如下: 上代码:关键代码用红色 series: [ { //name: '香港18区人口密度', type: 'map', mapType: 'jiangsu', ...
- React native 之设置IOS的图标,名称和启动图(下篇文章会讲到RN的android的相关设置)
1.首先,app的名称: 如图所示:我的工程名叫BOOk 在BOOk下面的info.plist的文件里设置app的相关信息:比如Bundle name就是设置APP的名称 2.App的图标:(这里注意 ...
- 蚂蚁金服 Service Mesh 渐进式迁移方案|Service Mesh Meetup 实录
小蚂蚁说: 本文是基于在 Service Mesher Meetup 上海站的主题分享<蚂蚁金服 Service Mesh 渐进式迁移方案>内容整理,完整的分享 PPT 获取方式见文章底部 ...
- 【五】php 面向对象
面向对象 概念:按类进行分类,类是表示彼此之间可能互不相同,但是具有一些共同点的对象集合 多态性:不同的类对同一操作可以有不同的行为 继承:允许我们使用子类在类之间创建层次关系 类 关键字:class ...
- WebStorm破解方法
http://www.jianshu.com/p/85266fa16639 http://idea.lanyus.com/ webstorm 入门指南 破解方法 1. 下载的WebStorm http ...
- js全选 反选
// 全选 反选 allChoose: function (o) { var obj = $.extend(true, { id: "#id", name: "name& ...
- 数据库锁机制(以MySQL为例)
选自:https://blog.csdn.net/aluomaidi/article/details/52460844 https://www.zhihu.com/question/51513268/ ...
- <script src="../build/browser.min.js"></script> 是用来里面babel工具把ES6的语法转成ES5
<!DOCTYPE html> <html> <head> <script src="../build/react.js">< ...
- 使用VSCode如何从github拉取项目
转载自:https://blog.csdn.net/sunqy1995/article/details/81517159 1.开vscode使用CTRL+`或者点击查看到集成终端打开控制终端 2. 在 ...
- leecode第六十二题(不同路径)
class Solution { public: int uniquePaths(int m, int n) { ||n==) ; vector<vector<int>> pa ...