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

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

学无止境,精益求精

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

如有不明白,请参考: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 难度:1   描述 输入n(n<100)个数,找出其中最小的数,将它与最前面的数交换后输出这些数.(如果这个第一个数就是最 ...

  2. cdoj 1328 卿学姐与诡异村庄 Label:并查集 || 二分图染色

    卿学姐与诡异村庄 Time Limit: 4500/1500MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit  ...

  3. TYVJ P3407 佳佳的魔法照片 Label:语文很重要 语文很重要 语文很重要

    描述 佳佳的魔法照片(mphoto.pas\c\cpp) [题目背景] 佳佳的魔法照片(Magic Photo):如果你看过<哈利•波特>,你就会知道魔法世界里的照片是很神奇的.也许是因为 ...

  4. css3+js打造炫酷图片展示

    <!DOCTYPE html> <html onselectstart="return false"> <!-- onselectstart=&quo ...

  5. 【BZOJ】2286: [Sdoi2011消耗战

    http://www.lydsy.com/JudgeOnline/problem.php?id=2286 题意:n个点的边加权树,m个询问,每次询问给出的k个点与结点1分离的最小代价.(n<=2 ...

  6. android注意事项

    今天做安卓设计,正在学习布局.在过程中遇到了几个小问题,感觉非常有必要记录分享出来. 1.string字符串不要出现"that's" ,要使用“that is”要不然会报错. 2. ...

  7. iOS应用内付费(IAP)开发步骤列表

    iOS应用内付费(IAP)开发步骤列表 前两天和服务端同事一起,完成了应用内付费(以下简称IAP, In app purchase)的开发工作.步骤繁多,在此把开发步骤列表整理如下.因为只是步骤列表, ...

  8. Linux watch 监控系统状态

    1.linux下watch命令的基本用法 # watch --helpUsage: watch [-dhntv] [--differences[=cumulative]] [--help] [--in ...

  9. PHP的学习--cookie和session--来自copy_02

    PHP的学习--cookie和session   最近读了一点<PHP核心技术与最佳实践>,看了cookie和session,有所收获,结合之前的认识参考了几篇博客,总结一下-- 1. P ...

  10. WinForm 窗体属性

    WinForm - C/S 客户端     B/S 网页端 客户端应用程序 - 是需要安装在用户电脑上才可以使用的程序特点:不需要联网也可以打开使用部分功能但是现在的情况是许多功能依然需要互联网的支持 ...