最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。

十年河东十年河西,莫欺少年穷

学无止境,精益求精

   本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧惭愧。

如有不明白,请参考: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 如何通过配置自动创建数据库<当模型改变时>的更多相关文章

  1. EF CodeFirst关于Mysql如何自动生成数据库表

    相对于sqlserver数据库,mysql的配置过程相对麻烦一些,我们从0讲起. 1.新建一个控制台应用程序 右键点击引用--管理NuGet程序包,搜索Mysql.Data.Entity并安装,安装完 ...

  2. EF自动创建数据库步骤之三(自定义数据库初始器)

    EF自动创建数据库需要我们告诉数据库如何进行初始化:如创建表后是否需要插入一些基础数据,是否 需要创建存储过程.触发器等.还有就是EF有三种初始化方式(参见下面三个类): DropCreateData ...

  3. EF自动创建数据库步骤之一(实体类写法)

    文章演示使用EF自动创建数据库第一个步骤创建实体类. 一.创建表映射实体类 using System; using System.Collections.Generic; using System.C ...

  4. 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统五 | 完善业务自动创建数据库

    教程预览 01 | 前言 02 | 简单的分库分表设计 03 | 控制反转搭配简单业务 04 | 强化设计方案 05 | 完善业务自动创建数据库 说明 这节来把基础的业务部分完善一下. 因为 IQue ...

  5. SpringBoot使用Hibernate,实现自动创建数据库表【博客数据库设计】

    我们准备设计博客,那就要设计数据库. 我们可以使用Hibernate来自动生成数据库. 博客数据库的结构: 实体类: 博客 Blog 博客分类 Type 博客标签 Tag 博客评论 Comment 用 ...

  6. EntityFramework SQLiteCodeFirst 自动创建数据库 关闭级联删除

    外键的级联删除: 如A表中有主键idA, B表中设置外键(ForeignKey)为A表中的主键idA, 当A表中的记录被删除时, B表中所有引用此条记录的记录(即所有外键为idA的记录)将自动被删除 ...

  7. sql2008 计划自动创建数据库分区【转】

    本文转自:http://jingyan.baidu.com/article/6b97984d9a26ec1ca3b0bf77.html sql2008 计划自动创建数据库分区 固定增量的数据,自动创建 ...

  8. centos 安装oracle 11g r2(二)-----监听配置与创建数据库实例

    centos 安装oracle 11g r2(二)-----监听配置与创建数据库实例 一.监听配置(命令:netca) 1.以 oracle 用户输入命令,启动图形化工具配置监听 [oracle@lo ...

  9. EF自动创建数据库步骤之二(继承DbContext类)

    创建好表实体类后,接着就是创建数据库上下文(继承DbContext)并将实体类添加进来. 代码示例如下: using DBClientEntity; using System; using Syste ...

随机推荐

  1. ACM 水池数目

    水池数目 时间限制:3000 ms  |  内存限制:65535 KB 难度:4   描述 南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地 ...

  2. [Cocos2d-x For WP8]Layer 层

        层(CCLayer) 从概念上说,层就是场景里的背景. CCLayer同样是CCNode的子类,通常用addChild方法添加子节点.CCLayer对象定义了可描绘的区域,定义了描绘的规则.C ...

  3. win8.1上wamp环境中利用apache自带ab压力测试工具使用超简单讲解

    2015.10.4apache自带ab压力测试工具使用:本地环境:win8.1 wampserver2.5 -Apache-2.4.9-Mysql-5.6.17-php5.5.12-64b 可以参考一 ...

  4. svn 回滚到上一个版本shell 脚本

    #!/bin/sh ############################## # -- # # author jackluo # # Email net.webjoy@gmail.com # ## ...

  5. 《自制编程语言》笔记:使用yacc与lex制作简单计算器

    1.代码 1.1)test.l 1.2)test.y 1.3)Makefile (因为是在linux环境下,所以使用了Makefile) 2.编译与运行 2.1)编译 2.2)运行 1.代码(也可以在 ...

  6. 如何将maven项目导入MyEclipse

    一.安装maven第一步:下载一个免安装版的apache-maven-3.0.3.zip解压后,配置环境变量 新建M2_HOME:   在path后面添加  %M2_HOME%\bin;   第二步: ...

  7. sencha 安装、学习

     sencha touch 是Extjs 的手机版,Extjs是创建富客户端的AJAX应用中的重量级框架,sencha touch当然就是面向触摸设备的重量级js框架,在做基于桌面的网页时经常用的js ...

  8. Missing number

    Missing number 题目: Description There is a permutation without two numbers in it, and now you know wh ...

  9. 1022. D进制的A+B (20)

    1022. D进制的A+B (20) 时间限制 100 ms 内存限制 32000 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 输入两个非负10进制整数A和 ...

  10. 快排java实现

    package sort; public class QuickSort { public static final int cutoff = 3; /** * insertion sort * * ...