(为什么这么写,我记不太清了。大致步骤相同,不过我推荐的这个比我写的好。愿:在程序的路上多多学习,共同进步!奥利给!!!)
一、在Models 新建两个数据库类
这个是数据库需要生成的类基础
public class User
{
[Key]
public string ID { get; set; }
[MaxLength()]
public string Name { get; set; }
public int Age { get; set; }
[MaxLength()]
public string Phone { get; set; }
public string DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public Department Department { get; set; }
}
public class Department
{
[Key]
public string ID { get; set; }
[MaxLength()]
public string Name { get; set; }
}
二、新建文件夹MysqlDbContext,然后新建类MysqlContext (注意文件夹的名字,不要跟类名一样)
然后建立表与数据库关系映射
public class MysqlContext : DbContext
{
public MysqlContext(DbContextOptions options) : base(options)
{
}
//建立表与模型的映射关系
public DbSet User { get; set; }
public DbSet Department { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
三、添加依赖项
依赖项右键 》》管理NuGet 包》》浏览
搜索这两个,注意安装的 版本号 ,是core 2.x的 你安装 3.x 会报错
我安装的是2.2.6
Microsoft.EntityFrameworkCore.Tool