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 ...
随机推荐
- [ACM训练] DEV C++如何处理不能调试
复试上机一定要用DEV C++,使用不熟练,出现一些问题,记录如下: 1.DEV C++ 不能调试 (1)tools->compiler option->settings:linker里设 ...
- Code[VS]1690 开关灯 题解
Code[VS]1690 开关灯 题解 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description: YYX家门前 ...
- 蒟蒻修养之cf橙名计划2
29 由于第一篇没写题意导致大部分神题题解已经完全不知道在说啥了...所以还是重开一篇保平安... [303A]题意:求三个长度为$n(n<=10^5)$的排列$a,b,c$使得$a_i+b_i ...
- bug: 在使用HMSegmentedControl时,设置selectionIndicatorEdgeInsets对左右边界没有用
若设置了 self.tabSegmented.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe; 则必须使用sel ...
- 应用的启动视图 LauchView
@interface AppDelegate () @property(strong,nonatomic) UIImageView *launchImaViewO; @property(strong, ...
- iOS Xcode7免证书真机调试
在Xcode 7 正式发布的日子里,苹果再次给开发者带来了惊喜,从此以后只要是真机调试的时候,不再需要花99刀去购买开发者证书,但是如果APP需要上架依旧还是需要购买开发者证书的.这个惊喜对正在学习i ...
- 深入浅出 - Android系统移植与平台开发(八)- HAL Stub框架分析
作者:唐老师,华清远见嵌入式学院讲师. 1. HAL Stub框架分析 HAL stub的框架比较简单,三个结构体.两个常量.一个函数,简称321架构,它的定义在:@hardware/libhardw ...
- 李洪强iOS经典面试题132-版本控制
面试过程中,可能会问及一些关于版本控制的问题,理解下SVN和Git的原理,记住常用命令即可. SVN SVN 是集中式源代码管理工具 概念: 1> Repository 代码仓库,保存代码的仓库 ...
- Struts基础详解
1.web.xml配置: <filter> <filter-name>Struts2</filter-name> <filter-class> org. ...
- java 中的2个接口 Comparable和Comparator
像Integer.String这些类型的数据都是已经实现Comparable接口的,所以对这些类型可以直接通过Arrays.sort(...)和Collections.sort(...)方法进行排序. ...