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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM