EntityFramewrok Codefirst 数据库初始化

我们希望当程序运行时自动完成数据库的创建并预置初始值。自己的Context名为 DataBaseContet

有两种方法:

1、在Global.asax中添加  Database.SetInitializer<DataBaseContext>(new DatabaseInitializer());

2、配置文件中添加 contexts 节点, 节点中指定类名与命名空间

<entityFramework>
    <contexts>
      <context type="DataBase.DataBaseContext, DataBase" disableDatabaseInitialization="false">
        <databaseInitializer type="DataBase.DatabaseInitializer, DataBase" />
      </context>
    </contexts>
    <defaultConnectionFactory type="DataBase.DataBaseContext, DataBase">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

其中 DataBaseContext为:

namespace DataBase
{
    public class DataBaseContext : DbContext
    {
        public DataBaseContext()
            : base("default")
        {

            //是否启用延迟加载:
            //  true:   延迟加载(Lazy Loading):获取实体时不会加载其导航属性,一旦用到导航属性就会自动加载
            //  false:  直接加载(Eager loading):通过 Include 之类的方法显示加载导航属性,获取实体时会即时加载通过 Include 指定的导航属性
            this.Configuration.LazyLoadingEnabled = true;
            this.Configuration.AutoDetectChangesEnabled = true;  //自动监测变化,默认值为 true
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
        public DbSet<UserModels> UserContext { get; set; }
        public DbSet<PigModels> PigContext { get; set; }
    }
}

自定义的数据初始化方法:DatabaseInitializer,其中继承的是DropCreateDatabaseAlways 只为演示用, 实际项目中根据需要选择。

namespace DataBase
{
    public class DatabaseInitializer : DropCreateDatabaseAlways<DataBaseContext>
    {
        protected override void Seed(DataBaseContext context)
        {
            UserModels m1 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张一",
                UserNumber = "0001",
                UserBirthDay = "1990.1.1",
                UserMail = "[email protected]",
                UserPhone = "13100001111",
                Password="aaaaaa"
            };

            UserModels m2 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张二",
                UserNumber = "0002",
                UserBirthDay = "1989.12.12",
                UserMail = "[email protected]",
                UserPhone = "13100002222",
                Password = "aaaaaa"
            };

            UserModels m3 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张三",
                UserNumber = "0003",
                UserBirthDay = "1989.12.12",
                UserMail = "[email protected]",
                UserPhone = "13100003333",
                Password = "aaaaaa"
            };

            try { // 写数据库 

            context.UserContext.Add(m1);
            context.UserContext.Add(m2);
            context.UserContext.Add(m3);
            context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx) { }
            base.Seed(context);
        }

    }
}

具体步骤:

首先通过NuGet工具安装EntityFramework,本人用的为6.0版本。

1、建立实体类:

namespace DatabaseModels
{
    public class UserModels
    {
        [Required]
        [Key]
        public string UserGUID { get; set; }
        [Required]
        [Display(Name = "用户名")]
        public string  UserName { get; set; }
        [Display(Name = "用户工号")]
        public string UserNumber { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密码")]
        public string Password { get; set; }
        [Display(Name = "出生日期")]
        public string UserBirthDay { get; set; }
        [Display(Name = "电话号")]
        public string UserPhone { get; set; }
        [Display(Name = "邮箱")]
        public string UserMail { get; set; }

    }
}

2、建立Context 继承 DbContext

namespace DataBase
{
    public class DataBaseContext : DbContext
    {
        public DataBaseContext()
            : base("default")
        {

            //是否启用延迟加载:
            //  true:   延迟加载(Lazy Loading):获取实体时不会加载其导航属性,一旦用到导航属性就会自动加载
            //  false:  直接加载(Eager loading):通过 Include 之类的方法显示加载导航属性,获取实体时会即时加载通过 Include 指定的导航属性
            this.Configuration.LazyLoadingEnabled = true;
            this.Configuration.AutoDetectChangesEnabled = true;  //自动监测变化,默认值为 true
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
        public DbSet<UserModels> UserContext { get; set; }
            }
}

3、创建数据初始方法

namespace DataBase
{
    public class DatabaseInitializer : DropCreateDatabaseAlways<DataBaseContext>
    {
        protected override void Seed(DataBaseContext context)
        {
            UserModels m1 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张一",
                UserNumber = "0001",
                UserBirthDay = "1990.1.1",
                UserMail = "[email protected]",
                UserPhone = "13100001111",
                Password="aaaaaa"
            };

            UserModels m2 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张二",
                UserNumber = "0002",
                UserBirthDay = "1989.12.12",
                UserMail = "[email protected]",
                UserPhone = "13100002222",
                Password = "aaaaaa"
            };

            UserModels m3 = new UserModels()
            {
                UserGUID = Guid.NewGuid().ToString(),
                UserName = "张三",
                UserNumber = "0003",
                UserBirthDay = "1989.12.12",
                UserMail = "[email protected]",
                UserPhone = "13100003333",
                Password = "aaaaaa"
            };

            try { // 写数据库 

            context.UserContext.Add(m1);
            context.UserContext.Add(m2);
            context.UserContext.Add(m3);
            context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx) { }
            base.Seed(context);
        }

    }
}

4、

方法一、在Global.asax中 添加 Database.SetInitializer<DataBaseContext>(new DatabaseInitializer());

或者:方法二:在配置文件中添加节点:

<contexts>
      <context type="DataBase.DataBaseContext, DataBase" disableDatabaseInitialization="false">
        <databaseInitializer type="DataBase.DatabaseInitializer, DataBase" />
      </context>
    </contexts>
时间: 2024-08-08 10:55:49

EntityFramewrok Codefirst 数据库初始化的相关文章

Code-First 数据库初始化策略

原文:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx 有四种不同的数据库初始化策略: CreateDatabaseIfNotExists:这是默认的初始值设定项.顾名思义,如果每个配置都不存在,它将创建数据库.但是,如果更改模型类,然后使用此初始化程序运行应用程序,则会引发异常. DropCreateDatabaseIfModelChange

EntityFramework Code-First 简易教程(三)-------数据库初始化

现在我们来学习,当数据库初始化的时候,Code First怎样设置数据库的名字. 下面的图显示了数据库初始化的工作流程,根据传入给context基类的构造函数的参数来初始化: 根据上面的图,context基类的构造函数可以传入如下参数: 无参数 参数为数据库名称 参数为连接字符串 无参数的构造函数: 如果不传参数给context基类的构造函数,它就会在我们本地创建一个以{命名空间}.{Context类名}为名字的数据库.比如下面代码会创建一个名字为SchoolDataLayer.Context的

DB Initialization(数据库初始化)[EF Code-First系列]

前面的例子中,我们已经看到了Code-First自动为我们创建数据库的例子. 这里我们将要学习的是,当初始化的时候,Code-First是怎么决定数据库的名字和服务的呢??? 下面的图,解释了这一切!!! 这个图解释了,数据库初始化的流程,是基于我们在上下文类中的构造函数中传递的参数. 在上面的图中,context类中的base构造器中,可以填入下面的参数: 无参数(No Parameter) 数据库的名字(Database Name) 连接字符串的名字(Connection String Na

EF CodeFirst简介、默认约定、数据库初始化策略

CodeFirst 工作流程 创建或修改领域类-->使用数据注解或者Fluent API来配置领域类-->使用自动数据库迁移技术或者基于代码的数据库迁移技术来创建数据库. CodeFirst默认约定 约定就是一系列的默认规则,通过这些规则,在使用EF Code-First的时候,可以自动的基于你的领域类配置概念模型.默认约定的命名空间:System.Data.Entity.ModelConfiguration.Conventions; ①schema(模式)  默认情况下,EF会为所有的数据库

【译】第31节---数据库初始化策略

原文:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx 在第一次运行Code-First应用程序后已经创建了一个数据库,但是第二次启动时呢?每次运行应用程序时会创建一个新的数据库吗?生产环境怎么样?更改域模型时,如何更改数据库?要处理这些情况,必须使用一个数据库初始化策略. 有四种不同的数据库初始化策略: CreateDatabaseIfNot

EF codefirst 数据库迁移

如果出现 未能加载文件或程序集“Microsoft.VisualStudio.Shell, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或它的某一个依赖项.系统找不到指定的文件. 重新安装EF 命令Install-Package EntityFramework 在此之后 主要是3步走: 1:Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDbC

Entity Framework数据库初始化四种策略

策略一:数据库不存在时重新创建数据库 复制内容到剪贴板 程序代码 Database.SetInitializer<testContext>(new CreateDatabaseIfNotExists<testContext>()); 策略二:每次启动应用程序时创建数据库 复制内容到剪贴板 程序代码 Database.SetInitializer<testContext>(new DropCreateDatabaseAlways<testContext>())

EntityFramework CodeFirst 数据库迁移

参考: https://msdn.microsoft.com/en-us/data/jj591621 http://www.itnose.net/detail/6105449.html http://www.tuicool.com/articles/Q7JRR32 打开:工具 --> NuGet包管理器 --> 程序包管理控制台,按下面的步骤使用相应的命令 //使能迁移功能 命令1. Enable-Migrations -ContextTypeName WebTest.Models.TestD

DbContext 那些事 —— 数据库初始化

数据库初始化 上图,这个图解释了,数据库初始化的流程,是基于我们在上下文类中的构造函数中传递的参数. 在上面的图中,context类中的base构造器中,可以填入下面的参数: 无参数(No Parameter) 数据库的名字(Database Name) 连接字符串的名字(Connection String Name) 无参数 1 using System; 2 using System.Collections.Generic; 3 using System.Data.Entity; 4 usi