首页 > 代码库 > EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>

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 = "081309201"},
                new Student{Name = "戚永景", Sex = "", StudentNum = "081309202"},
                new Student{Name = "刘华丽", Sex = "", StudentNum = "081309203"},
                new Student{Name = "薛正钦", Sex = "", StudentNum = "081309204"},
                new Student{Name = "王松涛", Sex = "", StudentNum = "081309205"},
                new Student{Name = "王自龙", Sex = "", StudentNum = "081309206"},
                new Student{Name = "高其峰", Sex = "", StudentNum = "081309207"},
                new Student{Name = "陈欣欣", Sex = "", StudentNum = "081309208"},
                new Student{Name = "陈丽阳", Sex = "", StudentNum = "081309209"}
           };
            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=1,CourseID=1,StudentScore=90},
                new Score{ StudentID=2,CourseID=1,StudentScore=91},
                new Score{ StudentID=3,CourseID=1,StudentScore=92},
                new Score{ StudentID=4,CourseID=1,StudentScore=93},
                new Score{ StudentID=5,CourseID=1,StudentScore=94},
                new Score{ StudentID=6,CourseID=1,StudentScore=95},
                new Score{ StudentID=7,CourseID=1,StudentScore=96},
                new Score{ StudentID=8,CourseID=1,StudentScore=97},
                new Score{ StudentID=9,CourseID=1,StudentScore=98}
            };
            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(10)]
        public string Name { get; set; }//姓名
        [StringLength(2)]
        public string Sex { get; set; }//性别
        [StringLength(20)]
        public string StudentNum { get; set; }//学号
    }

    public class Course
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(20)]
        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 如何通过配置自动创建数据库<当模型改变时>