開發環境
編譯器: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 的那個程序集