EF 4.3 CodeBased 数据迁移演练

  1. 首先第一步:创建一个 MigrationsCodeDemo控制台程序;
  2. 第二步:添加最新版本EntityFramework NuGet package 到这个项目里:
    • Tools –> Library Package Manager –> Package Manager Console.
    • Run the ‘Install-Package EntityFramework’ command
  3. 第三步:添加一个Blog类和一个继承自DbContext的BlogContext:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace MigrationsCodeDemo
    {
        public class Blog
        {
            public int BlogId { get; set; }
            public string Name { get; set; }
       
        }
    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
     
    namespace MigrationsCodeDemo
    {
        public class BlogContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
        }
    }
  4. 第五步:在控制台入口Program.cs文件里写下如下代码:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace MigrationsCodeDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BlogContext())
                {
                    db.Blogs.Add(new Blog { Name = "Another Blog " });
                    db.SaveChanges();
     
                    foreach (var blog in db.Blogs)
                    {
                        Console.WriteLine(blog.Name);
                    }
                }
            }
        }
     
    }

      准备工作做好了,运行这个程序,就就会发现一个名称为 MigrationsCodeDemo.BlogContext数据库就会出现在你的.\SQLEXPRESS 里

  5. 数据库生成之后不可能就能满足所有以后的需求的,如果我们要更改现有的数据库怎么办?(EF4.3强大的数据迁移功能就体现出来了)
    • 我们给现有的blog类添加一个Url 属性试试看
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
       
      namespace MigrationsCodeDemo
      {
          public class Blog
          {
              public int BlogId { get; set; }
              public string Name { get; set; }
              public string Url { get; set; }
           
          }
      }

        如果你就这样直接再次运行程序的话,肯定会报错的饿,因为数据库不再匹配你的Model,

      ”The model backing the 'BlogContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).” 

    • 根据错误提示,接下来需要使用Code First Migrations to update the database;第一步就是启用迁移为我们的项目
      1. Run the ‘Enable-Migrations’ command in Package Manager Console

    • 上面的命令执行之后,在你的项目里就会新建一个文件加,文件夹里有两个文件,分别是Configuration 和InitialCreate migration

    • 接下来我们就可以使用EF的Migration来为我们的Blog添加新的属性并同步到数据库了,
      1. Run the ‘Add-Migration AddBlogUrl’ command in Package Manager Console,之后项目的文件夹下就会新建一个AddBlogUrl migration文件
        namespace MigrationsCodeDemo.Migrations
        {
            using System.Data.Entity.Migrations;
             
            public partial class AddBlogUrl : DbMigration
            {
                public override void Up()
                {
                    AddColumn("Blogs", "Url", c => c.String());
                }
                 
                public override void Down()
                {
                    DropColumn("Blogs", "Url");
                }
            }
        }

          里面主要包括两个函数,其中up用于数据迁移,down用于数据回溯,当然如果觉得这些操作还不够可以自己手动修改里面的操作,

      2. 最后就是Run the ‘Update-Database’ command in Package Manager Console,这样我们对model的修改就会更新到数据库里,

    • 添加完字段之后,我们发现还是原来的设计更好,这时我们就需要回溯我们的数据库:
      Run the ‘Update-Database –TargetMigration:"InitialCreate"’ command in Package Manager Console.,此时数据库就又回到了刚开始建的是时候,

查看sql:我们在 Package Manager Console执行相关的命令之后,数据库就做出来相应的改变,如果我们想查看数据迁移过程中这些命令到底为我们做了什么,我们可以使用-script来获取各个migration的sql,比如我们migrations文件夹下只有两个migration

我们想查看InitialCreate具体执行了哪些脚本:我们可以Run the ‘Update-Database –TargetMigration:"InitialCreate"’ command in Package Manager Console,

查看AddBlogUrl具体执行了哪些脚本,我们可以Run the ‘Update-Database –TargetMigration:"AddBlogUrl"’ command in Package Manager Console,

一旦这些命令被执行,相关的.sql文件就会被打开在Visual Studio

注意Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you.这是MSDN上的原话,担心自己翻译的不准确就没有翻译,呵呵,

命令关键字总结:

  1. Install-Package EntityFramework
  2. Enable-Migrations
  3. Add-Migration
  4. Update-Database
  5. Update-Database –Verbose (相关的脚本会显示在Package Manager Console里,并最终应用到数据库)
  6. Update-Database -Script -SourceMigration:$InitialDatabase -TargetMigration:"AddBlogUrl" (其中AddBlogUrl是Migration Name,这是生成sql文件but instead of actually applying the changes)

原文:http://www.cnblogs.com/LittleFeiHu/archive/2012/02/20/2359324.html

原文地址:https://www.cnblogs.com/idoudou/p/2420983.html