Entity Framework CodeFirst数据迁移
前言
紧接着前面一篇博文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数据迁移的更多相关文章
- Entity Framework Migrations 数据迁移
在使用Entity Framework 过程中,经常会遇到需要变更model 的状况,此时可以使用Migrations ,将每次变更记录以便后续更换机器或是运行在生产环境,持久层可保持一致. 在Pac ...
- Entity Framework Code First 迁移
Entity Framework CodeFirst数据迁移 http://www.cnblogs.com/aehyok/p/3325459.html Entity Framework Code Fi ...
- entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败
警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...
- EF Code-First数据迁移
Code-First数据迁移 首先要通过NuGet将EF升级至最新版本. 新建MVC 4项目MvcMigrationDemo 添加数据模型 Person 和 Department,定义如下: usi ...
- 【EF】EF Code-First数据迁移
Code-First数据迁移 首先要通过NuGet将EF升级至最新版本. 新建MVC 4项目MvcMigrationDemo 添加数据模型 Person 和 Department,定义如下: usi ...
- 第二篇:Entity Framework CodeFirst & Model 映射
前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现 ...
- Entity Framework Codefirst的配置步骤
Entity Framework Codefirst的配置步骤: (1) 安装命令: install-package entityframework (2) 创建实体类,注意virtual关键字在导航 ...
- 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...
- ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)
ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...
随机推荐
- ASP.NET MVC 5 入门教程 (2) 控制器Controller
文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-controller.html 上一节:ASP.NET MVC ...
- Javascript设计模式之我见:迭代器模式
大家好!本文介绍迭代器模式及其在Javascript中的应用. 模式介绍 定义 提供一种方法顺序一个聚合对象中各个元素,而又不暴露该对象内部表示. 类图及说明 Iterator抽象迭代器 抽象迭代器负 ...
- JQuery上传文件插件Uploadify使用笔记
新工作的第一份任务就是给实现 限制Uploadify 上传文件格式为图片 测试出来报错,选择了非图片文件,提示错误后,再选择其他文件,上传时还是包含了之前清空的非图片文件 最后实现效果的代码是 //上 ...
- [转]细说MySQL Explain和Optimizer Trace简介
在开发过程中,对每个上线的SQL查询指纹(query figerprint)的质量都应有估算:而估算DB查询质量最直接的方法,就是分析其查询执行计划( Query Execution Plan ,即Q ...
- 【MPI学习1】简单MPI程序示例
有了apue的基础,再看mpi程序多进程通信就稍微容易了一些,以下几个简单程序来自都志辉老师的那本MPI的书的第七章. 现在ubuntu上配置了一下mpich的环境: http://www.cnblo ...
- storm如何保证at least once语义?
背景 前期收到的问题: 1.在Topology中我们可以指定spout.bolt的并行度,在提交Topology时Storm如何将spout.bolt自动发布到每个服务器并且控制服务的CPU.磁盘等资 ...
- 【POJ各种模板汇总】(写在逆风省选前)(不断更新中)
1.POJ1258 水水的prim……不过poj上硬是没过,wikioi上的原题却过了 #include<cstring> #include<algorithm> #inclu ...
- 编写高质量代码改善C#程序的157个建议[动态数组、循环遍历、对象集合初始化]
前言 软件开发过程中,不可避免会用到集合,C#中的集合表现为数组和若干集合类.不管是数组还是集合类,它们都有各自的优缺点.如何使用好集合是我们在开发过程中必须掌握的技巧.不要小看这些技巧,一旦在开 ...
- Bootstrap3.0学习第二十一轮(JavaScript插件——工具提示)
详情请查看http://aehyok.com/Blog/Detail/27.html 个人网站地址:aehyok.com QQ 技术群号:206058845,验证码为:aehyok 本文文章链接:ht ...
- session,cookie
Session 和cookie的学习 cookie cookie的建立 setcookie(name,value); setcookie(name,value,expiration,path,host ...