注意:一旦正常后,每次数据库有变化,做如下两步:

1. Enable-Migrations

2.update-database

背景

code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据迁移功能来完成。

要求
  1. 已安装NuGet
过程示例
  1. //原model
//原model
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. public class Lesson {
  5. public int lessonID { get; set; }
  6. [Required]
  7. [MaxLength(50)]
  8. public string lessonName { get; set; }
  9. [Required]
  10. public string teacherName { get; set; }
  11. public virtual UserInfo UserInfo{get;set;}
  12. }
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Lesson {
public int lessonID { get; set; }
[Required]
[MaxLength(50)]
public string lessonName { get; set; }
[Required]
public string teacherName { get; set; }
public virtual UserInfo UserInfo{get;set;}
}
  1. //新model
//新model
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. public class Lesson {
  5. public int lessonID { get; set; }
  6. [Required]
  7. [MaxLength(50)]
  8. public string lessonName { get; set; }
  9. [Required]
  10. [MaxLength(10)]
  11. public string teacherName { get; set; }
  12. public virtual UserInfo UserInfo{get;set;}
  13. }
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Lesson {
public int lessonID { get; set; }
[Required]
[MaxLength(50)]
public string lessonName { get; set; }
[Required]
[MaxLength(10)]
public string teacherName { get; set; }
public virtual UserInfo UserInfo{get;set;}
}

注:区别在于,我们给teacherName属性加了一个长度限制。

接下来,我们将开始持久化此model至数据库中(我们现在只是对属性作修改,此时数据库中此字段的长度为nvarchar(max),并不是nvarchar(10))

1:在config中配置数据库连接:

  1. <connectionStrings>
  2. <add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PC\SQLEXPRESS" providerName="System.Data.SqlClient" />
  3. </connectionStrings>
  <connectionStrings>
<add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PC\SQLEXPRESS" providerName="System.Data.SqlClient" />
</connectionStrings>

2:打开NuGet控制台:

3:运行命令Enable-Migrations

可能会出现如下错误:

Checking if the context targets an existing database... Detected database created with a database initializer. Scaffolded migration '201212090821166_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter. Code First Migrations enabled for project MvcApplication1.

此时项目会出现如下文件夹:

打开configuation.cs,将作出如下修改:

  1. public Configuration()
  2. {
  3. AutomaticMigrationsEnabled = true;
  4. }
        public Configuration()
{
AutomaticMigrationsEnabled = true;
}

再次执行Update-Database:

因为我把长度从max改为10,在更新数据结构时,它认为此操作会导致数据丢失,如下:

Specify the '-Verbose' flag to view the SQL statements being applied to the target database. No pending code-based migrations. Applying automatic migration: 201212090848057_AutomaticMigration. Automatic migration was not applied because it would result in data loss.

如果确保没事,只需给此命令加个强制执行的参数即可:

Enable-Migrations -Force

最后再次执行:Update-Database

数据库中的原数据也没有丢失!

3:

Code First Migrations更新数据库结构(数据迁移) 【转】的更多相关文章

  1. ASP.NET MVC4 新手入门教程特别篇之一----Code First Migrations更新数据库结构(数据迁移)修改Entity FrameWork 数据结构(不删除数据)

    背景 code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的 ...

  2. Code First Migrations更新数据库结构(数据迁移)

    背景 code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建 (DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们 ...

  3. Code First Migrations更新数据库结构的具体步骤

    一.打开程序包管理器控制台 当你的实体模型与数据库架构不一致时,引发以下错误:The model backingthe 'SchoolContext' context has changed sinc ...

  4. 转载Code First Migrations更新数据库架构的具体步骤

    [转载] Code First Migrations更新数据库结构的具体步骤 我对 CodeFirst 的理解,与之对应的有 ModelFirst与  DatabaseFirst ,三者各有千秋,依项 ...

  5. 使用Code first 进行更新数据库结构(数据迁移)

    CodeFirst 背景  code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会 ...

  6. (转)使用Migrations更新数据库结构(Code First )

    原文地址:http://blog.csdn.net/luoyeyu1989/article/details/8275237 背景 code first起初当修改model后,要持久化至数据库中时,总要 ...

  7. Code First 下自动更新数据库结构(Automatic Migrations)

    示例 Web.config <?xml version="1.0" encoding="utf-8"?> <configuration> ...

  8. Code First 更新数据库结构(简单实现方法:会删除原来的数据)

    之前在 http://www.cnblogs.com/mmcmmc/p/3833265.html 写到关于“Code First 更新数据库结构”的东西. 可是由于某种原因,新手们会出现各种问题,好了 ...

  9. Entity Framework 6 Code First的简单使用和更新数据库结构

    一.安装Entity Framework 6 在项目中右击选择“管理NuGet程序包",联机搜索Entity Framework,点击安装 二.配置数据库连接 在App.config中加入数 ...

随机推荐

  1. 另一种方式实现事务码SE16里的结果集修改

    注: 这种方法不同于网上流传的在调试器里修改fcode的那种解决方案. 使用场景:我们需要直接在开发系统的事务码SE16里修改某些结果集的值,但是在SE16的工具栏里看不见修改按钮: 解决方案 使用/ ...

  2. 模拟,找次品硬币,Counterfeit Dollar(POJ 1013)

    题目链接:http://poj.org/problem?id=1013 解题报告: 1.由于次品的重量不清楚,用time['L'+1]来记录各个字母被怀疑的次数.为负数则轻,为正数则重. 2.用zer ...

  3. [APIO/CTSC 2007]数据备份

    嘟嘟嘟 这竟然是一道贪心题,然而我在不看题解之前一直以为是dp. 首先最优的配对一定是相邻两个建筑物配对,所以我们求出差分数组,就变成了在n - 1个数中选出不相邻的k个数,使这k个数的和最小. 贪心 ...

  4. XCode项目配置可访问 非 https 接口的方法

    打开项目的info.plist文件,右键- open as sourceCode .在代码中添加: <key>NSAppTransportSecurity</key> < ...

  5. python time模块计算程序耗时

    import time start = time.clock() end = time.clock() consume_time = end - start

  6. 整个简历的讲解(falling+mimic+refidet)

    1.解决方案 下边缘: a.论文的数据来自kitti,gt数据来自于激光雷达,利用kitti自带的开发包先将激光雷达的数据映射到图片的二维平面,每个x,y会生成对应的d(x,y),即depth.再对每 ...

  7. Cesium.js隐藏logo等信息

    css: .cesium-widget-credits{ display:none!important;}js: var viewer = new Cesium.Viewer('cs', { anim ...

  8. 【洛谷P1039】侦探推理

    侦探推理 题目链接 这是一道恶心至极的模拟题 我们可以枚举罪犯是谁,今天是星期几,从而判断每个人说的话是真是假 若每个人说的话的真假一致,且说谎话的人数<=k且说真话的人数<=m-k,就是 ...

  9. ListView与SimpleAdapter

    Adapter可以视作控件与数据之间的桥梁 对ListView做自由布局和填充需要使用到Adapter,这里我们采用SimpleAdapter. 简单来说: 1.定义一个ListItem,其数据结构是 ...

  10. Android学习笔记_33_Widget时钟(MetaData)

    Widgets在文档docs\guide\topics\appwidgets\index.html下 Android中AppWidget的分析与应用:AppWidgetProvider 一.在 And ...