SQLServer

添加引用:

  1. dotnet add package Microsoft.EntityFrameworkCore.Design
  2. dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Design: Shared design-time components for Entity Framework Core tools.

生成模型类

通过数据库中的表生成模型类和 dbContext:

  1. dotnet ef dbcontext scaffold "Server=(local);Database=CoreBB;User=sa;Pwd=123456" "Microsoft.EntityFrameworkCore.SqlServer" -o .\Models -f

MySQL

添加引用:

  1. dotnet add package Microsoft.EntityFrameworkCore.Design
  2. dotnet add package Pomelo.EntityFrameworkCore.MySql
  3. dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet

生成模型类

  1. dotnet ef dbcontext scaffold "Server=localhost;Database=sakila;Uid=YourUserName;Pwd=YourUserPassword;SslMode=none" "Pomelo.EntityFrameworkCore.MySql" -d -f -o Models

复制 SQLServer 数据库至 MySQL

这种情况下两个数据库的引用都需要添加:

  1. dotnet add package Microsoft.EntityFrameworkCore.Design
  2. dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  3. dotnet add package Pomelo.EntityFrameworkCore.MySql

然后先通过 SQLServer 生成模型类,再更改绑定字符串,最后通过 EF Core 更新数据库至 MySQL。

通过 SQLServer 生成的模型类中的 dbContext.cs:

  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  2. {
  3. if (!optionsBuilder.IsConfigured)
  4. {
  5. optionsBuilder.UseSqlServer("Server=(local);Database=CoreBB;User=sa;Pwd=123456");
  6. }
  7. }

将其更改为:

  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  2. {
  3. if (!optionsBuilder.IsConfigured)
  4. {
  5. optionsBuilder.UseMySql("Server=118.x.x.x;Database=CoreBB;User=remote;Pwd=123456");
  6. }
  7. }

注意保证此处的账户在 MySQL 中拥有足够的权限。

最后是运行 EF Core 命令更新数据库:

  1. dotnet ef migrations add InitialCreate
  2. dotnet ef database update