反向工程
1、根据数据库表来反向生成实体类,安装:
install-package Microsoft.EntityFrameworkCore.SqlServer、
install-package Microsoft.EntityFrameworkCore.Tools
2、程序包管理器控制台执行如下命令:
Scaffold-DbContext "Server=DESKTOP-7K7ADF7;Database=EFCore2; User Id=sa;Password=XXX;TrustServerCertificate=True;Trusted_Connection=True;MultipleActiveResultSets=True" Microsoft.EntityFrameworkCore.SqlServer
Scaffold-DbContext会自动生成如下代码:
MyDBContext:
public partial class MyDbContext : DbContext
{
public MyDbContext()
{
}
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public virtual DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
=> optionsBuilder.UseSqlServer("Server=DESKTOP-7K7ADF7;Database=EFCore2; User Id=sa;Password=LGF3c5c8@;MultipleActiveResultSets=True;Trusted_Connection=True;TrustServerCertificate=True;");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>(entity =>
{
entity.ToTable("T_Persons");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
实体类:
public partial class Person
{
public long Id { get; set; }
public string Name { get; set; } = null!;
public double Height { get; set; }
}
3、如果生成之后,数据库又有新的更新,我们要重新生成,则需要使用 -Force
Scaffold-DbContext "Server=DESKTOP-7K7ADF7;Database=EFCore2; User Id=sa;Password=XXX;TrustServerCertificate=True;Trusted_Connection=True;MultipleActiveResultSets=True" Microsoft.EntityFrameworkCore.SqlServer -Force
注意事项
1、生成的实体类可能不能满足项目的要求,需要手动修改或者增加配置。
2、数据库变动后,重新运行反向工程工具,之前对文件所做的所有修改都会丢失。