SQLServer
添加引用:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design: Shared design-time components for Entity Framework Core tools.
生成模型类
通过数据库中的表生成模型类和 dbContext:
dotnet ef dbcontext scaffold "Server=(local);Database=CoreBB;User=sa;Pwd=123456" "Microsoft.EntityFrameworkCore.SqlServer" -o .\Models -f
MySQL
添加引用:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet
生成模型类
dotnet ef dbcontext scaffold "Server=localhost;Database=sakila;Uid=YourUserName;Pwd=YourUserPassword;SslMode=none" "Pomelo.EntityFrameworkCore.MySql" -d -f -o Models
复制 SQLServer 数据库至 MySQL
这种情况下两个数据库的引用都需要添加:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Pomelo.EntityFrameworkCore.MySql
然后先通过 SQLServer 生成模型类,再更改绑定字符串,最后通过 EF Core 更新数据库至 MySQL。
通过 SQLServer 生成的模型类中的 dbContext.cs:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(local);Database=CoreBB;User=sa;Pwd=123456");
}
}
将其更改为:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySql("Server=118.x.x.x;Database=CoreBB;User=remote;Pwd=123456");
}
}
注意保证此处的账户在 MySQL 中拥有足够的权限。
最后是运行 EF Core 命令更新数据库:
dotnet ef migrations add InitialCreate
dotnet ef database update