前言

紧接着前面一篇博文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. IL指令大全

    IL是.NET框架中中间语言(Intermediate Language)的缩写.使用.NET框架提供的编译器可以直接将源程序编译为.exe或.dll文件,但此时编译出来的程序代码并不是CPU能直接执 ...

  2. cocos2d-x 3.0以上版本字体设置问题

    cocos2d-x中的万年大坑,字体总算是有比较好的结局办法了.之前都是CCLabelTTF,CCLabelBMFont,CCLabelAtlas什么的,我只想说一句:好难用!毕竟是做游戏,那么难看的 ...

  3. Unity Networking API文档翻译(一):Networking概述

    写在翻译前的话:      我使用过Photon,研究过Ulink这些Unity提供的多人在线游戏服务器组件,这些商业组件虽然很好很强大.但是对于一个独立开发者来说,4000多软妹币还是点多.总想找一 ...

  4. Coding the Matrix (0):映射、复数和域

    1. 非常好的 Python 教程 <深入 Python 3.0> 以及 IBM 开发社区的博客探索 Python. 2. 子集: s 是 S 的子集 >>>S = {2 ...

  5. Beta版本贡献比

    学号             姓名    贡献率 031302301  毕容甲   25%031302302  蔡逸轩   25%031302430  肖阳      25%031302418  黄彦 ...

  6. 关于Jquery 操作Cookie 取值错误

    使用JQuery操作cookie时 发生取的值不正确的问题: 结果发现cookie有四个不同的属性: 名称,内容,域,路径 $.cookie('the_cookie'); // 读取 cookie $ ...

  7. Eclipse-将svn上的项目转化成相应的项目

    这里假设svn上的项目为maven项目 首先从svn检出项目 其中项目名称code可自己定义更改新的名称 从svn检出的项目结构 然后将项目转化成相关的项目 转换加载中 加载/下载 maven相关内容 ...

  8. Cocos2d-X3.0 刨根问底(五)----- Node类及显示对象列表源码分析

    上一章 我们分析了Cocos2d-x的内存管理,主要解剖了 Ref.PoolManager.AutoreleasePool这三个类,了解了对象是如何自动释放的机制.之前有一个类 Node经常出现在各种 ...

  9. 38.Android之ListView简单学习(一)

    android中ListView用的很普遍,今天来学习下,本篇主要以本地数据加载到listview,后面会学习从网络获取数据添加到listview. 首先改下布局文件: <?xml versio ...

  10. Codeforces 650C Table Compression

    传送门 time limit per test 4 seconds memory limit per test 256 megabytes input standard input output st ...