1. 程式人生 > 實用技巧 >DotNet Core 3.1 EF Core 資料庫遷移(Migration)

DotNet Core 3.1 EF Core 資料庫遷移(Migration)

開發環境

編譯器:VS2019
資料庫:SqlServer 2019

執行環境

DotNet Core SDK(3.1.400)

SqlServer遷移方式

依賴包

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer

使用遷移命令需要的依賴包

Microsoft.EntityFrameworkCore.Tools
EntityFramework
Microsoft.EntityFrameworkCore.Design

遷移命令

1.建立第一個遷移
Add-Migration InitialCreate   

2.建立資料庫和架構
Update-Database 

如果在實體中需要新增CreatedTimestamp 欄位

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedTimestamp { get; set; }
}

執行如下命令建立新遷移:

Add-Migration AddBlogCreatedTimestamp

Update-Database

如果執行Update-Database異常需要刪除上一個新增的遷移命令

刪除上一個新增的遷移命令
Remove-Migration

appsettings.json配置

新增ConnectionString節點

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  
  "ConnectionString": {
    "SqlServer": "server=.;database=NetCoreDemo;uid=sa;pwd=123"
  }
}

Startup.cs配置如下

public void ConfigureServices(IServiceCollection services)
{
    string constr = Configuration.GetSection("ConnectionString:SqlServer").Value;
    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(constr));

    services.AddControllersWithViews();
}

MySql遷移方式

依賴包

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
MySql.Data.EntityFrameworkCore

appsettings.json配置

新增ConnectionString節點

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionString": {
    "MySql": "Data Source=localhost;port=3306;database=NetCoreDemo;User Id=root;Password=12345"
  }
}


Startup.cs配置如下

public void ConfigureServices(IServiceCollection services)
{
    var constr = Configuration.GetSection("ConnectionString:MySql").Value;
    services.AddDbContext<MyDbContext>(
          options => options.UseMySQL(constr)
          );

    services.AddControllersWithViews();
}

在依次執行上述遷移命令即可

注意執行命令時必須預設專案必須選擇繼承了DbContext 的那個程式集

參考地址:https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/?tabs=vs