EF 迁移数据库
迁移是使用代码生成或修改数据库结构
导入 Microsoft.EntityFrameworkCore.Design可以使用迁移或逆向工程的命令
代码准备
实体类
public class Users { public int Id { get; set; } public string UserName { get; set; } public string PassWord { get; set; } }
实体类配置
class UsersConfig : IEntityTypeConfiguration<Users> { public void Configure(EntityTypeBuilder<Users> builder) { builder.ToTable("T_Users"); } }
DBContext
class MyDbContext : DbContext { public DbSet<Users> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseMySql("Server=127.0.0.1;port=3306;Database=test;uid=root;pwd=xxxxxx;Character Set=utf8;", new MySqlServerVersion(new Version(8, 0, 21))); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } }
初始化迁移
dotnet ef migrations add InitialCreate
按照ef代码迁移架构到数据库
dotnet ef database update
查看数据库