前言

紧接着前面一篇博文Entity Framework CodeFirst尝试

我们知道无论是“Database First”还是“Model First”当模型发生改变了都可以通过Visual Studio设计视图进行更新,那么对于Code First如何更新已有的模型呢?今天我们简单介绍一下Entity Framework的数据迁移功能。

Entity Framework配置

当我们对项目进行Entity Framework进行安装引用的时候,同时生成了两个配置文件

packages.config文件:

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
</packages>

App.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

packages.config内容比较简单,首先是EF自身版本,然后在安装过程中根据当前应用的.NET Framework版本配置了“targetFramework”,因为不同的.NET Framework版本对应的EF程序集不同,这在安装过程中会自动识别并配置。

App.config中自动添加了“entityFramework”配置节,在EF包安装过程中自动根据当前环境配置了“defaultConnectionFactory”, “defaultConnectionFactory”是EF默认的连接配置,只有在没有配置连接字符串时生效。

配置了数据库链接字符串的App.config配置文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="CodeFirstTest" connectionString="Data Source=.;Database=CodeFirstTest;UID=sa;PWD=sa123;" providerName="System.Data.SqlClient"></add>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

CodeFirst 数据迁移

现在让我们在上一篇文章的Entity Framework CodeFirst尝试 的基础上给Order添加一个"Employee”属性,然后运行,不出意外的话你将看到如下异常:

从异常信息我们可以看出,EF已经检测到模型发生了改变,建议我们使用”Code First Migrations”对模型进行更新。

在开始Code First数据库迁移之前,我们先对上一节编写的OrderTestContext类进行修改添加默认构造函数,因为Code First Migrations将会使用数据库上下文的默认构造函数进行数据迁移操作(尽管没有默认构造函数所有的数据操作都能正常进行,但是对于数据迁移这是必须的),因此我们需要添加一个默认构造函数,并且该构造函数中必须传入我们的数据库连接名称,否则将会把更新应用到EF默认数据库上。下面是我们的OrderTestContext:

    public class OrderTestContext:DbContext
{
public OrderTestContext():base("CodeFirstTest")
{ } public OrderTestContext(string connectionName)
: base(connectionName)
{
}
public DbSet<Order> Orders { get;set;} public DbSet<OrderDetail> OrderDetails { get; set; }
}

下面我们将借助于”Code First Magrations” 进行模型更新。然后找到如下图所示的位置

1.在“程序包管理器控制台”键入命令:Enable-Migrations -ProjectName  CodeFirstTest

如果多次执行此命令可以添加-Force参数

添加后,项目中添加了一个名为Migrations的文件夹

查看Configuration文件中的代码为:

namespace CodeFirstTest.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<CodeFirstTest.OrderTestContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
} protected override void Seed(CodeFirstTest.OrderTestContext 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. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}

方法Seed中可以进行数据迁移后的数据初始化工作,将在每次迁移之后运行。如上代码所示,AddOrUpdate是IDbSet<TEntity>的扩展方法,如果指定条件的数据不存在,则会添加,如果存在,会更新。所以,如果数据是通过此方法来初始化的,在与业务更新之后,再次进行数据迁移后,还是会被还原。

还有一个名为InitialCreate的类,配置生成数据库的细节:

namespace CodeFirstTest.Migrations
{
using System;
using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Orders",
c => new
{
ID = c.Int(nullable: false, identity: true),
Customer = c.String(),
OrderDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.ID); CreateTable(
"dbo.OrderDetails",
c => new
{
ID = c.Int(nullable: false, identity: true),
Product = c.String(),
OrderID = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Orders", t => t.OrderID, cascadeDelete: true)
.Index(t => t.OrderID); } public override void Down()
{
DropIndex("dbo.OrderDetails", new[] { "OrderID" });
DropForeignKey("dbo.OrderDetails", "OrderID", "dbo.Orders");
DropTable("dbo.OrderDetails");
DropTable("dbo.Orders");
}
}
}

3.执行“Add-Migration AddEmployee”命令,添加一个名为AddEmployee的迁移

4.执行“Update-Database”命令,更新数据库架构

如果更新数据库存在冲突而不能执行更新,可以添加 -Force强制执行,例如:“Update-Database -Force”

5.设置自动迁移

每次都通过控制台来进行迁移太过麻烦,可以设置为自动迁移。

  1. AutomaticMigrationsEnabled:获取或设置 指示迁移数据库时是否可使用自动迁移的值。

  2. AutomaticMigrationDataLossAllowed:获取或设置 指示是否可接受自动迁移期间的数据丢失的值。如果设置为false,则将在数据丢失可能作为自动迁移一部分出现时引发异常。

    3.在Global.asax.cs中添加初始化策略

Database.SetInitializer(new MigrateDatabaseToLatestVersion<OrderTestContext, Configuration>());

代码调用实例

            using (var db = new OrderTestContext("CodeFirstTest"))
{
Order Order = new Order();
Order.Customer = "aehyok";
Order.OrderDate = DateTime.Now;
db.Orders.Add(Order);
db.SaveChanges(); IQueryable<Order> Orders = from Orderes in db.Orders
select Orderes;
foreach (Order O in Orders)
{
Console.WriteLine("OrderID is {0},Customer is {1}", O.ID, O.Customer);
}
}

调用结果展示

有两条数据,一条是上一篇博文添加的数据,第二条就是今天测试添加的。

Entity Framework CodeFirst数据迁移的更多相关文章

  1. Entity Framework Migrations 数据迁移

    在使用Entity Framework 过程中,经常会遇到需要变更model 的状况,此时可以使用Migrations ,将每次变更记录以便后续更换机器或是运行在生产环境,持久层可保持一致. 在Pac ...

  2. Entity Framework Code First 迁移

    Entity Framework CodeFirst数据迁移 http://www.cnblogs.com/aehyok/p/3325459.html Entity Framework Code Fi ...

  3. entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败

    警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...

  4. EF Code-First数据迁移

    Code-First数据迁移  首先要通过NuGet将EF升级至最新版本. 新建MVC 4项目MvcMigrationDemo 添加数据模型 Person 和 Department,定义如下: usi ...

  5. 【EF】EF Code-First数据迁移

    Code-First数据迁移  首先要通过NuGet将EF升级至最新版本. 新建MVC 4项目MvcMigrationDemo 添加数据模型 Person 和 Department,定义如下: usi ...

  6. 第二篇:Entity Framework CodeFirst & Model 映射

    前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现 ...

  7. Entity Framework Codefirst的配置步骤

    Entity Framework Codefirst的配置步骤: (1) 安装命令: install-package entityframework (2) 创建实体类,注意virtual关键字在导航 ...

  8. 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用

    上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...

  9. ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)

    ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...

随机推荐

  1. Jenkins进阶系列之——09配置Linux系统ssh免密码登陆

    ssh认证的完整描述:https://www.ibm.com/developerworks/cn/linux/security/openssh/part1/ 说明:点我去查看 今天我们只说生成ssh的 ...

  2. json跨域原理及解决方法

    这一篇文章呢,主要是之前一直听别人讲json跨域跨域,但是还是一头雾水,只知其一,于是一怒之下,翻阅各种资料,如果有不正确的地方,劳烦指正一下^_^ 首先,先了解浏览器有一个很重要安全性限制,即为同源 ...

  3. 如何远程断点调试本地localhost项目

    前言 对于一般开发网站的IDE自带的服务器是都跑在 localhost 地址上的.(如下图的asp.net) 而这种地址是只能在本机通过 localhost 或 127.0.0.1 地址访问到,而无法 ...

  4. 浅析Javascript

    Javascript是一种脚本语言,从出生就被唾弃,一开始人们使用它只是为了解决诸如页面数据校验之类的问题.它基于prototype的面向对象实现一度被认为很丑很难用,甚至很多身处一线Web开发者都不 ...

  5. 用javascript实现简单排序算法

    声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢! 本文为楼主自己的学习记录文章,若有不当之处请斧正. 本文主要记录排序算法 [冒泡排序] 感觉这个是最简单的排序算法了.直接引用维基百科里的 ...

  6. bluebird

    nodejs-使用request和bluebird编写的http请求模块   http://blog.csdn.net/o6875461/article/details/44594545

  7. AaronYang的C#私房菜[二][提供编程效率的技巧]

    前言 我的文章简单易懂,能学到东西.因为复杂的东西,讲起来,好累.阅读者只是膜拜,学不到东西,就是没用的东西,好多文章都是看不下去.我写不出来<大话设计模式>那种为了读者的书,因为没有时间 ...

  8. 史上最全的javascript知识点总结,浅显易懂。

    来源于:http://blog.csdn.net/qiushi_1990/article/details/40260471 一,认识javascript1-1为什么学习JavaScript一).你知道 ...

  9. zabbix 客户端的安装

    这里我们在客户端安装就是用rpm的安装方式了: 在我使用RPM安装的时候遇到了一个错误 [root@git src]# rpm -ivh http://repo.zabbix.com/zabbix/3 ...

  10. 【转】Oracle之物化视图

    原文地址:http://www.cnblogs.com/Ronger/archive/2012/03/28/2420962.html 物化视图是一种特殊的物理表,“物化”(Materialized)视 ...