ef core 数据迁移
1 安装 EF Core 命令行工具
安装命令
dotnet tool install --global dotnet-ef
2 搭建好项目 entity,map,dbContext
在项目中添加如下引用:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.SqlServer
3.1 添加 entities
SysUserEntity 如下
namespace ConsoleApp_EFMigration.Entities { public class SysUserEntity { /// <summary> /// Id /// </summary> public string Id { get; set; } /// <summary> /// 用户账号 /// </summary> public string UserCode { get; set; } /// <summary> /// 用户名 /// </summary> public string UserName { get; set; } } }
3.2 添加 maps
SysUserMap 如下
using ConsoleApp_EFMigration.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace ConsoleApp_EFMigration.Maps { public class SysUserMap : IEntityTypeConfiguration<SysUserEntity> { public void Configure(EntityTypeBuilder<SysUserEntity> builder) { builder.ToTable("SysUser"); // 映射到表 SysUser builder.HasKey(c => c.Id); // 表 主键为 Id } } }
3.3 添加 dbContexts
数据库 Test 的上下文类如下
using ConsoleApp_EFMigration.Entities; using ConsoleApp_EFMigration.Maps; using Microsoft.EntityFrameworkCore; namespace ConsoleApp_EFMigration.DbContexts { /// <summary> /// 数据库 Test 上下文类 /// </summary> public class TestDbContext : DbContext { public TestDbContext() { Database.EnsureCreated(); } public DbSet<SysUserEntity> SysUsers { get; set; } public DbSet<SysRoleEntity> SysRoles { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new SysUserMap()); modelBuilder.ApplyConfiguration(new SysRoleMap()); base.OnModelCreating(modelBuilder); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); string connStr = "Server=****;Database=Test;Uid=sa;Pwd=****;TrustServerCertificate=True;"; optionsBuilder.UseSqlServer(connStr); // SqlServer 数据库 } } }
3 在项目.csproj文件目录下,文件地址栏输入 cmd
4 添加迁移
在 cmd 窗口中输入添加迁移命令如下:
dotnet ef migrations add First
// 撤销迁移 dotnet ef migrations add AddProvinceName2 命令
dotnet ef migrations remove
5 应用迁移
在cmd窗口中执行以下迁移命令
dotnet ef database update
6 查看迁移结果
自动创建了数据库(连接字符串指定的数据库)和对应的表。
参考链接
https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli
https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli