EF Core 数据库迁移(Migration)

工具与环境介绍

1.开发环境为vs 2015

2.mysql EF Core支持采用  Pomelo.EntityFrameworkCore.MySql   源代码地址(https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

场景

设计两张表 用户表(user)和发帖表(user)

一个用户对应多个用户

Coding Begin

1.新建项目(新建一个空console项目)

image

2.添加Nuget.config

增加两个feed,一个是Pomelo(mysql ef core的支持),一个是nuget

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="Pomelo" value="https://www.myget.org/F/pomelo/api/v3/index.json" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2" />
  </packageSources>
</configuration>

 

image

3.在project.json中增加ef core的依赖,同时增加EF Tool(用于数据库的迁移)

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0"
    },
    "Pomelo.EntityFrameworkCore.MySql": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

 

4.增加User,Post实体 和DB数据库上下文文件

代码分别如下:
public class User  
 {      
     public int Id { set; get; }     
     
     public string UserName { set; get; }    
   
     public string Password { set; get; }  
 }

public class Post
{     
      public int Id { set; get; }     
      public string Title { set; get; }     
      public string Description { set; get; }    
      public DateTime CreatedDate { set; get; }     
      public int UserId { set; get; }
}

  public class DB : DbContext
    {

        public DbSet<User> Users { set; get; }

        public DbSet<Post> Posts { set; get; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         => optionsBuilder
             .UseMySql(@"Server=localhost;database=migrationtest;uid=root;pwd=Password12!;");
}
 

5.通过Migration生成数据库

在vs中的“程序包管理器控制台”中输入如下两个命令
Add-Migration init(执行此命令项目生成一个目录(Migration))
Update-Database init

执行之前

image
执行Add-Migration init(生成Migration文件夹)
image
 
执行 Update-Database init
image
执行命令之后,数据库生成
image
Post表
image

6.往数据库插入数据

image

image

 

7.修改实体字段,在post实体中增加一个字段和修改一个字段的名字

修改之后的post如下

public class Post
{    
     public int Id { set; get; }     
   
     public string Title { set; get; }
 
     public string Hint { set; get; }

     public DateTime CreatedDate { set; get; }    
   
     public int UserId { set; get; }   
  
     public string Remark { set; get; }

 
}

8.执行迁移的命令

Add-Migration updatedb
Update-Database updatedb

image

执行迁移之后的post表

image

posted @ 2016-09-01 21:43  nele  阅读(30271)  评论(3编辑  收藏  举报