.Net Core3.1使用EFCore進行數據遷移(Migration)


開發環境

編譯器:VS2019

運行環境

DotNet Core SDK(3.1.8) 

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.UseMySQL(connstr, m => m.MigrationsAssembly("User.API")); 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.UseMySQL(connstr, m => m.MigrationsAssembly("User.API")); ); services.AddControllersWithViews(); } 

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

注意執行命令時必須默認項目必須選擇繼承了DbContext 的那個程序集


免責聲明!

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



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