Entity Framework使用Code First模式管理数据库

 更新时间:2022年3月5日 16:46  点击:406 作者:.NET开发菜鸟

一、管理数据库连接

1、使用配置文件管理连接之约定

在数据库上下文类中,如果我们只继承了无参数的DbContext,并且在配置文件中创建了和数据库上下文类同名的连接字符串,那么EF会使用该连接字符串自动计算出数据库的位置和数据库名。比如,我们的数据库上下文定义如下:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConventionConfigure.EF
{
    /// <summary>
    /// 继承无参数的DbContext
    /// </summary>
    public class SampleDbEntities :DbContext
    {
        public SampleDbEntities()
        {
            // 数据库不存在时创建数据库
            Database.CreateIfNotExists();
        }
    }
}

在配置文件中定义的连接字符串如下:

<connectionStrings>
    <add name="SampleDbEntities" connectionString="Data Source=.;Initial Catalog=TestDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>

定义的连接字符串中name的value值和创建的数据库上下文类的类名相同,这样EF会使用该连接字符串执行数据库操作,究竟会发生什么呢?

运行程序,Program类定义如下:

using ConventionConfigure.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConventionConfigure
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new SampleDbEntities())
            { }

            Console.WriteLine("创建成功");
            Console.ReadKey();
        }
    }
}

当运行应用程序时,EF会寻找我们的数据库上下文类,即“SampleDbEntities”,并在配置文件中寻找和它同名的连接字符串,然后它会使用该连接字符串计算出应该使用哪个数据库provider,之后检查数据库位置,之后会在指定的位置创建一个名为TestDb.mdf的数据库文件,同时根据连接字符串的Initial Catalog属性创建了一个名为TestDb的数据库。创建的数据库结构如下:

查看创建后的数据库,会发现只有一张迁移记录表。

2、使用已经存在的ConnectionString

如果我们已经有了一个定义数据库位置和名称的ConnectionString,并且我们想在数据库上下文类中使用这个连接字符串,连接字符串如下:

<connectionStrings>
    <add name="AppConnection" connectionString="Data Source=.;Initial Catalog=TestDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>

以上面创建的数据库TestDb作为已经存在的数据库,新添加实体类Student,使用已经存在的ConnectionString查询数据库的Student表,Student实体类定义如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExistsConnectionString.Model
{
    [Table("Student")]
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        public int Age { get; set; }
    }
}

我们将该连接字符串的名字传入数据库上下文DbContext的有参构造函数中,数据库上下文类定义如下:

using ExistsConnectionString.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExistsConnectionString.EF
{
    public class SampleDbEntities : DbContext
    {
        public SampleDbEntities()
            : base("name=AppConnection")
        {

        }

        // 添加到数据上下文中
        public virtual DbSet<Student> Students { get; set; }
    }
}

上面的代码将连接字符串的名字传给了DbContext类的有参构造函数,这样一来,我们的数据库上下文就会开始使用该连接字符串了,在Program类中输出Name和Age字段的值:

using ExistsConnectionString.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExistsConnectionString
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new SampleDbEntities())
            {
                foreach (var item in context.Students)
                {
                    Console.WriteLine("姓名:"+item.Name+" "+"年龄:"+item.Age);
                }
            }
        }
    }
}

运行程序,发现会报下面的错误:

出现上面报错的原因是因为数据库上下文发生了改变,与现有数据库不匹配。解决方案:

把数据库里面的迁移记录表删掉或者重命名即可。

重新运行程序,结果如下:

注意:如果在配置文件中还有一个和数据库上下文类名同名的ConnectionString,那么就会使用这个同名的连接字符串。无论我们对传入的连接字符串名称如何改变,都是无济于事的,也就是说和数据库上下文类名同名的连接字符串优先权更大。(即约定大于配置)

3、使用已经存在的连接

通常在一些老项目中,我们只会在项目中的某个部分使用EF Code First,同时,我们想对数据上下文类使用已经存在的数据库连接,如果要实现这个,可将连接对象传给DbContext类的构造函数,数据上下文定义如下:

using ExistsDbConnection.Model;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExistsDbConnection.EF
{
    public class SampleDbEntities :DbContext
    {
        public SampleDbEntities(DbConnection con)
            : base(con, contextOwnsConnection: false)
        {

        }

        public virtual DbSet<Student> Students { get; set; }
    }
}

这里要注意一下contextOwnsConnection参数,之所以将它作为false传入到上下文,是因为它是从外部传入的,当上下文超出了范围时,可能会有人想要使用该连接。如果传入true的话,那么一旦上下文出了范围,数据库连接就会立即关闭。

Program类定义如下:

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using ExistsDbConnection.EF;

namespace ExistsDbConnection
{
    class Program
    {
        static void Main(string[] args)
        {
            // 读取连接字符串
            string conn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString;
            // DbConnection是抽象类,不能直接实例化,声明子类指向父类对象
            DbConnection con = new SqlConnection(conn);
            using (var context = new SampleDbEntities(con))
            {
                foreach (var item in context.Students)
                {
                    Console.WriteLine("姓名:" + item.Name + " " + "年龄:" + item.Age);
                }
            }

            Console.WriteLine("读取完成");
            Console.ReadKey();
        }
    }
}

运行程序,结果如下:

二、管理数据库创建

首次运行EF Code First应用时,EF会做下面的这些事情:
1、检查正在使用的DbContext类。
2、找到该上下文类使用的connectionString。
3、找到领域实体并提取模式相关的信息。
4、创建数据库。
5、将数据插入系统。

一旦模式信息提取出来,EF会使用数据库初始化器将该模式信息推送给数据库。数据库初始化器有很多可能的策略,EF默认的策略是如果数据库不存在,那么就重新创建;如果存在的话就使用当前存在的数据库。当然,我们有时也可能需要覆盖默认的策略,可能用到的数据库初始化策略如下:

CreateDatabaseIfNotExists:CreateDatabaseIfNotExists:顾名思义,如果数据库不存在,那么就重新创建,否则就使用现有的数据库。如果从领域模型中提取到的模式信息和实际的数据库模式不匹配,那么就会抛出异常。

DropCreateDatabaseAlways:如果使用了该策略,那么每次运行程序时,数据库都会被销毁。这在开发周期的早期阶段通常很有用(比如设计领域实体时),从单元测试的角度也很有用。

DropCreateDatabaseIfModelChanges:这个策略的意思就是说,如果领域模型发生了变化(具体而言,从领域实体提取出来的模式信息和实际的数据库模式信息失配时),就会销毁以前的数据库(如果存在的话),并创建新的数据库。

MigrateDatabaseToLatestVersion:如果使用了该初始化器,那么无论什么时候更新实体模型,EF都会自动地更新数据库模式。这里很重要的一点是:这种策略更新数据库模式不会丢失数据,或者是在已有的数据库中更新已存在的数据库对象。MigrateDatabaseToLatestVersion初始化器只有从EF4.3才可用。

1、设置初始化策略

EF默认使用CreateDatabaseIfNotExists作为默认初始化器,如果要覆盖这个策略,那么需要在DbContext类中的构造函数中使用Database.SetInitializer方法,下面的例子使用DropCreateDatabaseIfModelChanges策略覆盖默认的策略。数据库上下文类定义如下:

using InitializationStrategy.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationStrategy.EF
{
    public class SampleDbEntities : DbContext
    {
        public SampleDbEntities()
            : base("name=AppConnection")
        {
            // 使用DropCreateDatabaseIfModelChanges策略覆盖默认的策略
            Database.SetInitializer<SampleDbEntities>(new DropCreateDatabaseIfModelChanges<SampleDbEntities>());
        }

        // 添加到数据上下文中
        public virtual DbSet<Student> Students { get; set; }
    }
}

这样一来,无论什么时候创建上下文类,Database.SetInitializer()方法都会被调用,并且将数据库初始化策略设置为DropCreateDatabaseIfModelChanges。

Student领域实体类新增加Email和Address两个属性:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationStrategy.Model
{
    [Table("Student")]
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        public int Age { get; set; }

        public string Email { get; set; }

        public string Address { get; set; }
    }
}

Program类定义如下:

using InitializationStrategy.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationStrategy
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new SampleDbEntities())
            {
                foreach (var item in context.Students)
                {

                }
            }

            Console.WriteLine("创建成功");
            Console.ReadKey();
        }
    }
}

运行程序后,数据库表结构如下:

注意:如果处于生产环境,那么我们肯定不想丢失已经存在的数据。这时我们就需要关闭该初始化器,只需要将null传给Database.SetInitlalizer()方法,如下所示:

public SampleDbEntities(): base("name=AppConnection")
{
Database.SetInitializer<SampleDbEntities>(null);
}

2、填充种子数据

到目前为止,无论我们选择哪种策略初始化数据库,生成的数据库都是一个空的数据库。但是许多情况下我们总想在数据库创建之后、首次使用之前就插入一些数据。此外,开发阶段可能想以admin的资格为其填充一些数据,或者为了测试应用在特定的场景中表现如何,想要伪造一些数据。

当我们使用DropCreateDatabaseAlways和DropCreateDatabaseIfModelChanges初始化策略时,插入种子数据非常重要,因为每次运行应用时,数据库都要重新创建,每次数据库创建之后在手动插入数据非常乏味。接下来我们看一下当数据库创建之后如何使用EF来插入种子数据。

为了向数据库插入一些初始化数据,我们需要创建满足下列条件的数据库初始化器类:

1、从已存在的数据库初始化器类中派生数据。
2、在数据库创建期间种子化。

下面演示如何初始化种子数据

1、定义领域实体类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationSeed.Model
{
    [Table("Employee")]
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }
}

2、创建数据库上下文

使用EF的Code First方式对上面的模型创建数据库上下文:

public class SampleDbEntities : DbContext
{
    public virtual DbSet<Employee> Employees { get; set; }
}

3、创建数据库初始化器类

假设我们使用的是DropCreateDatabaseAlways数据库初始化策略,那么初始化器类就要从该泛型类继承,并传入数据库上下文作为类型参数。接下来,要种子化数据库就要重写DropCreateDatabaseAlways类的Seed()方法,而Seed()方法拿到了数据库上下文,因此我们可以使用它来将数据插入数据库:

using InitializationSeed.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationSeed.EF
{

    /// <summary>
    /// 数据库初始化器类
    /// </summary>
    public class SeedingDataInitializer : DropCreateDatabaseAlways<SampleDbEntities>
    {
        /// <summary>
        /// 重写DropCreateDatabaseAlways的Seed方法
        /// </summary>
        /// <param name="context"></param>
        protected override void Seed(SampleDbEntities context)
        {
            for (int i = 0; i < 6; i++)
            {
                var employee = new Employee
                {
                  FirstName="测试"+(i+1),
                  LastName="工程师"
                };

                context.Employees.Add(employee);

            }
                base.Seed(context);
        }
    }
}

上面的代码通过for循环创建了6个Employee对象,并将它们添加给数据库上下文类的Employees集合属性。这里值得注意的是我们并没有调用DbContext.SaveChanges()方法,因为它会在基类中自动调用。

4、将数据库初始化器类用于数据库上下问类

using InitializationSeed.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationSeed.EF
{
    public class SampleDbEntities :DbContext
    {
        public SampleDbEntities()
            : base("name=AppConnection")
        {
            // 类型传SeedingDataInitializer
            Database.SetInitializer<SampleDbEntities>(new SeedingDataInitializer());
        }

        // 领域实体添加到数据上下文中
        public virtual DbSet<Employee> Employees { get; set; }
    }
}

5、Main方法中访问数据库

using InitializationSeed.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InitializationSeed
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new SampleDbEntities())
            {
                foreach (var item in context.Employees)
                {
                    Console.WriteLine("FirstName:"+item.FirstName+" "+"LastName:"+item.LastName);
                }
            }

            Console.WriteLine("读取完成");
            Console.ReadKey();
        }
    }
}

6、运行程序,查看结果

查看数据库

种子数据填充完成。

7、使用数据迁移的方式填充种子数据

使用数据迁移的方式会生成Configuration类,Configuration类定义如下:

namespace DataMigration.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<DataMigration.SampleDbEntities>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(DataMigration.SampleDbEntities context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}

重写Configuration类的Seed()方法也可以实现插入种子数据,重写Seed()方法:

namespace DataMigration.Migrations
{
    using DataMigration.Model;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<DataMigration.SampleDbEntities>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(DataMigration.SampleDbEntities context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            context.Employees.AddOrUpdate(
                 new Employee { FirstName = "测试1", LastName = "工程师" },
                 new Employee { FirstName = "测试2", LastName = "工程师" }

                );
        }
    }
}

使用数据迁移,然后查看数据库结果:

发现使用数据迁移的方式也将种子数据插入到了数据库中。

代码下载地址:点此下载

到此这篇关于Entity Framework使用Code First模式管理数据库的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

原文出处:https://www.cnblogs.com/dotnet261010/p/8035213.html

[!--infotagslink--]

相关文章

  • js URLdecode()与urlencode方法支持中文解码

    下面来介绍在js中来利用urlencode对中文编码与接受到数据后利用URLdecode()对编码进行解码,有需要学习的机友可参考参考。 代码如下 复制代码 ...2016-09-20
  • php中json_decode()和json_encode()用法与中文不显示解决办法

    本文章介绍了关于php中json_decode()和json_encode()用法与中文不显示解决办法,有需要的朋友可以参考一下下。 php中json_decode()和json_encode() 1.json_decode(...2016-11-25
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • VSCode 配置uni-app的方法

    这篇文章主要介绍了VSCode 配置uni-app的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • vscode安装git及项目开发过程

    这篇文章主要介绍了vscode安装git及项目开发过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-05-19
  • Vscode上使用SQL的方法

    这篇文章主要介绍了Vscode上使用SQL的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-01-26
  • PHP json_encode() 函数详解及中文乱码问题

    在 php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它。这个函数的功能是将数值转换成json数据存储格式。<&#63;php$arr = array ( 'Name'=>'希亚', 'Age'...2015-11-08
  • vscode搭建STM32开发环境的详细过程

    这篇文章主要介绍了vscode搭建STM32开发环境的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-05-02
  • 微信小程序二维码生成工具 weapp-qrcode详解

    这篇文章主要介绍了微信小程序 二维码生成工具 weapp-qrcode详解,教大家如何在项目中引入weapp-qrcode.js文件,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下...2021-10-23
  • VSCode C++多文件编译的简单使用方法

    这篇文章主要介绍了VSCode C++多文件编译的简单使用方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-29
  • 浅谈Vue开发人员的7个最好的VSCode扩展

    这篇文章主要介绍了浅谈Vue开发人员的7个最好的VSCode扩展,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
  • VSCode配置C#运行环境的完整步骤

    这篇文章主要给大家介绍了关于VSCode配置C#运行环境的完整步骤,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • vscode和cmake编译多个C++文件的实现方法

    这篇文章主要介绍了vscode和cmake编译多个C++文件的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • VS Code C/C++环境配置教程(无法打开源文件“xxxxxx.h”或者检测到 #include 错误,请更新includePath)(POSIX API)

    这篇文章主要介绍了VS Code C/C++环境配置教程(无法打开源文件“xxxxxx.h” 或者 检测到 #include 错误。请更新includePath) (POSIX API),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-08-13
  • IntelliJ IDEA 刷题利器 LeetCode 插件详解

    这篇文章主要介绍了IntelliJ IDEA 刷题利器 LeetCode 插件,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-08-21
  • Windows配置VSCode+CMake+Ninja+Boost.Test的C++开发环境(教程详解)

    这篇文章主要介绍了Windows配置VSCode+CMake+Ninja+Boost.Test的C++开发环境,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-05-12
  • 如何使用VSCode配置Rust开发环境(Rust新手教程)

    这篇文章主要介绍了如何使用VSCode配置Rust开发环境(Rust新手教程),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-27
  • C#利用QrCode.Net生成二维码(Qr码)的方法

    QrCode.Net是一个使用C#编写的用于生成二维码图片的类库,使用它可以非常方便的为WinForm、WebForm、WPF、Silverlight和Windows Phone 7应用程序提供二维码编码输出功能。可以将二维码文件导出为eps格式...2020-06-25
  • vscode通过Remote SSH远程连接及离线配置的方法

    这篇文章主要介绍了vscode通过Remote SSH远程连接及离线配置的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-16
  • .Net(c#)汉字和Unicode编码互相转换实例

    下面小编就为大家带来一篇.Net(c#)汉字和Unicode编码互相转换实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25