数据库准备
在数据库新建一个库students,然后创建如下一个表,这里演示使用的是MySQL
CREATE TABLE `student` ( `id` int NOT NULL, `class` varchar(255) DEFAULT NULL COMMENT '班级', `name` varchar(255) DEFAULT NULL COMMENT '姓名', `age` int DEFAULT NULL COMMENT '年龄', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
项目
新建一个空项目,安装如下三个nuget包
打开终端,到当前项目路径下,输入如下命令
dotnet ef dbcontext scaffold "server=127.0.0.1;uid=root;pwd=123456;database=students" Pomelo.EntityFrameworkCore.MySql
项目中就会自动创建这两个类
public partial class Student { public int Id { get; set; } /// <summary> /// 班级 /// </summary> public string? Class { get; set; } /// <summary> /// 姓名 /// </summary> public string? Name { get; set; } /// <summary> /// 年龄 /// </summary> public int? Age { get; set; } }
public partial class studentsContext : DbContext { public studentsContext() { } public studentsContext(DbContextOptions<studentsContext> options) : base(options) { } public virtual DbSet<Student> Students { get; set; } = null!; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #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 http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseMySql("server=127.0.0.1;uid=root;pwd=123456;database=students", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.33-mysql")); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.UseCollation("utf8mb4_0900_ai_ci") .HasCharSet("utf8mb4"); modelBuilder.Entity<Student>(entity => { entity.ToTable("student"); entity.Property(e => e.Id) .ValueGeneratedNever() .HasColumnName("id"); entity.Property(e => e.Age) .HasColumnName("age") .HasComment("年龄"); entity.Property(e => e.Class) .HasMaxLength(255) .HasColumnName("class") .HasComment("班级"); entity.Property(e => e.Name) .HasMaxLength(255) .HasColumnName("name") .HasComment("姓名"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); }
然后就可以查询数据库中的数据了
在默认情况下,生成的类都是放根目录下的,所以还需要优化一下,在刚刚命令后面加上--context-dir 和--output-dir 来指定存放的文件夹
dotnet ef dbcontext scaffold "server=127.0.0.1;uid=root;pwd=123456;database=students" Pomelo.EntityFrameworkCore.MySql --context-dir Data --output-dir Entities