EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。
十年河东十年河西,莫欺少年穷
学无止境,精益求精
本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧惭愧。
如有不明白,请参考:EF CodeFirst 创建数据库 及 EF CodeFirst增删改查之‘CRUD’
话不多说,直接上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EF_Test.DAL
{
public class StudentInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StudentContext>
{
protected override void Seed(StudentContext context)
{
//添加学生
var studentList = new List<Student>
{
new Student{Name = "陈依依", Sex = "女", StudentNum = ""},
new Student{Name = "戚永景", Sex = "女", StudentNum = ""},
new Student{Name = "刘华丽", Sex = "女", StudentNum = ""},
new Student{Name = "薛正钦", Sex = "男", StudentNum = ""},
new Student{Name = "王松涛", Sex = "男", StudentNum = ""},
new Student{Name = "王自龙", Sex = "男", StudentNum = ""},
new Student{Name = "高其峰", Sex = "男", StudentNum = ""},
new Student{Name = "陈欣欣", Sex = "女", StudentNum = ""},
new Student{Name = "陈丽阳", Sex = "女", StudentNum = ""}
};
studentList.ForEach(s => context.Students.Add(s));
context.SaveChanges();
//添加课程
var courseList = new List<Course>
{
new Course{ Name="数据结构"},
new Course{ Name="计算机原理"},
new Course{ Name="网络技术"}
};
courseList.ForEach(s => context.Courses.Add(s));
context.SaveChanges();
//添加分数
var scoreList = new List<Score>()
{
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=},
new Score{ StudentID=,CourseID=,StudentScore=}
};
scoreList.ForEach(s => context.Scores.Add(s));
context.SaveChanges();
}
}
}
模型类如下:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web; namespace EF_Test.DAL
{
public class Student
{
[Key]
public int Id { get; set; }
[Required]
[StringLength()]
public string Name { get; set; }//姓名
[StringLength()]
public string Sex { get; set; }//性别
[StringLength()]
public string StudentNum { get; set; }//学号
} public class Course
{
[Key]
public int Id { get; set; }
[Required]
[StringLength()]
public string Name { get; set; }//课程名称
} public class Score
{
[Key]
public int Id { get; set; } public int StudentScore { get; set; }//学生分数 public int StudentID { get; set; }//学生ID public int CourseID { get; set; }//课程ID public virtual Student Student { get; set; }//virtual关键字修饰,用于延迟加载 提高性能 只有显式调用时 属性==对象 public virtual Course Course { get; set; }//virtual关键字修饰,用于延迟加载 提高性能 只有显式调用时 属性==对象
} public class StudentContext : DbContext
{
public StudentContext()
: base("StudentContext")//指定连接字符串
{ }
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Score> Scores { get; set; } /// <summary>
/// OnModelCreating方法中的modelBuilder.Conventions.Remove语句禁止表名称正在多元化。如果你不这样做,所生成的表将命名为Students、Courses和Enrollments。相反,表名称将是Student、Course和Enrollment。开发商不同意关于表名称应该多数。本教程使用的是单数形式,但重要的一点是,您可以选择哪个你更喜欢通过包括或省略这行代码的形式。
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
OK,截止到这儿,您可能会问我,protected override void Seed()这个重写的方法什么时间执行呢?
在此,需要两点要求
1、在web.config中<entityFramework>接点下加入如下配置:
<contexts>
<context type="EF_Test.DAL.StudentContext, EF_Test">
<databaseInitializer type="EF_Test.DAL.StudentInitializer, EF_Test" />
</context>
</contexts>
根据上述类文件,我们应该明白EF_Test是个命名空间,EF_Test.DAL.StudentContext是数据库上下文,EF_Test.DAL.StudentInitializer是初始化类
2、加上了上述配置,还需模型结构发生改变时,程序才会自动执行Seed()方法,例如:将字段长度由50改为20
综上所述条件满足后,程序就会自动重新删除数据库并建立
@陈卧龙的博客
EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>的更多相关文章
- EF CodeFirst关于Mysql如何自动生成数据库表
相对于sqlserver数据库,mysql的配置过程相对麻烦一些,我们从0讲起. 1.新建一个控制台应用程序 右键点击引用--管理NuGet程序包,搜索Mysql.Data.Entity并安装,安装完 ...
- EF自动创建数据库步骤之三(自定义数据库初始器)
EF自动创建数据库需要我们告诉数据库如何进行初始化:如创建表后是否需要插入一些基础数据,是否 需要创建存储过程.触发器等.还有就是EF有三种初始化方式(参见下面三个类): DropCreateData ...
- EF自动创建数据库步骤之一(实体类写法)
文章演示使用EF自动创建数据库第一个步骤创建实体类. 一.创建表映射实体类 using System; using System.Collections.Generic; using System.C ...
- 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统五 | 完善业务自动创建数据库
教程预览 01 | 前言 02 | 简单的分库分表设计 03 | 控制反转搭配简单业务 04 | 强化设计方案 05 | 完善业务自动创建数据库 说明 这节来把基础的业务部分完善一下. 因为 IQue ...
- SpringBoot使用Hibernate,实现自动创建数据库表【博客数据库设计】
我们准备设计博客,那就要设计数据库. 我们可以使用Hibernate来自动生成数据库. 博客数据库的结构: 实体类: 博客 Blog 博客分类 Type 博客标签 Tag 博客评论 Comment 用 ...
- EntityFramework SQLiteCodeFirst 自动创建数据库 关闭级联删除
外键的级联删除: 如A表中有主键idA, B表中设置外键(ForeignKey)为A表中的主键idA, 当A表中的记录被删除时, B表中所有引用此条记录的记录(即所有外键为idA的记录)将自动被删除 ...
- sql2008 计划自动创建数据库分区【转】
本文转自:http://jingyan.baidu.com/article/6b97984d9a26ec1ca3b0bf77.html sql2008 计划自动创建数据库分区 固定增量的数据,自动创建 ...
- centos 安装oracle 11g r2(二)-----监听配置与创建数据库实例
centos 安装oracle 11g r2(二)-----监听配置与创建数据库实例 一.监听配置(命令:netca) 1.以 oracle 用户输入命令,启动图形化工具配置监听 [oracle@lo ...
- EF自动创建数据库步骤之二(继承DbContext类)
创建好表实体类后,接着就是创建数据库上下文(继承DbContext)并将实体类添加进来. 代码示例如下: using DBClientEntity; using System; using Syste ...
随机推荐
- 使用SQLAlchemy对Firebird数据库进行操作
来这个公司已经一周了,度过了开始的无聊日子准备正式准备做点东西了,这几天接触了一下文件数据库InterBase,尝试在Ubuntu上连接其开源版本Firebird,因为公司使用的是SQLAlchemy ...
- 【BZOJ3673】&&【BZOJ3674】: 可持久化并查集 by zky 可持久化线段树
没什么好说的. 可持久化线段树,叶子节点存放父亲信息,注意可以规定编号小的为父亲. Q:不是很清楚空间开多大,每次询问父亲操作后修改的节点个数是不确定的.. #include<bits/stdc ...
- hdu1232 并查集
1. hdu1232 2.链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232 3.总结:简单并查集 #include<iostream> # ...
- IOS面试题总结
iOS面试题: 一:网络理论知识的理解 1:Internet物理地址和IP地址转换采用什么协议 ARP(Address Resolution Protocol)地址解析协议 2:Internet采用哪 ...
- 使用 Eclipse C/C++ Development Toolkit 开发应用程序
使用 Eclipse C/C++ Development Toolkit 开发应用程序 (转) 来自http://blog.csdn.net/favory/article/details/189080 ...
- 清除BOM头源码
BOM: Byte Order Mark UTF-8 BOM又叫UTF-8 签名,其实UTF-8 的BOM对UFT-8没有作用,是为了支援UTF-16,UTF-32才加上的BOM,BOM签名的意思就是 ...
- mysql 主从同步原理
Replication 线程 Mysql的 Replication 是一个异步的复制过程,从一个 Mysql instace(我们称之为 Master)复制到另一个 Mysql instance(我们 ...
- 从就业面分析web前端开发工程师就业前景(2011.6)
案例一 公司名称:法国电信北京研发中心 工作地点:北京 联系方式:hao.luan@orange-ftgroup.com 栾先生 岗位名称:web 前端开发工程师 岗位要求: 1. 计算机或相关专业本 ...
- OpenCV 3.0 CvMat and cv::Mat Conversion
After OpenCV 3.0, CvMat cannot be directly converted to cv::Mat, we need to use function cvarrToMat( ...
- [CareerCup] 17.4 Maximum of Two Numbers 两数中的较大值
17.4 Write a method which finds the maximum of two numbers. You should not use if-else or any other ...