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 ...
随机推荐
- BZOJ 1015 题解
1015: [JSOI2008]星球大战starwar Description 很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武器统治者整个星系.某一天,凭着一个偶然的机遇,一支反抗军摧毁了帝 ...
- POJ 2402 Palindrome Numbers
题目链接 水题,LA我居然没找到在那里. #include <cstdio> #include <cstring> #include <string> #inclu ...
- 【BZOJ1257】【CQOI2007】余数之和sum
Description 给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值,其中k mod i表示k除以i的余数.例如j(5, ...
- C#:实现快捷键自定义设置(转)
项目开发过程中,需要实现类似有道词典的软件设置中的自定义快捷键功能,如下图所示: 当我们相继按下Ctrl+Alt+M的时候,软件就会自动将快捷键显示在文本框中. 最终的效果如下图所示: private ...
- 李洪强漫谈iOS开发[C语言-050]-doWhile统计用户输入字符
- Log4cplus使用
Log4cplus使用¶ 1.1 简介 log4cplus是C++编写的开源日志系统,前身是java编写的log4j日志系统.log4cplus具有线程安全.灵活.以及多粒度控制的特点,通过将信息划分 ...
- [LintCode] Count and Say 计数和读法
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221 ...
- 如何判断js中对象的类型
1.typeof 形如 var x = "xx"; typeof x == 'string' typeof(x); 返回类型有:'undefined' "string&q ...
- centos MariaDB10.1.X galera cluster
[mariadb] name = MariaDB baseurl = http://yum.mariadb.org/10.1.12/centos6-amd64 gpgkey=https://yum.m ...
- JS的Touch事件们,触屏时的js事件
丫的,终于找到了JS在平板电脑上的事件!!! iphone.ipod Touch.ipad触屏时的js事件 1.Touch事件简介 pc上的web页面鼠标会产生onmousedown.on ...