在使用efcode来操作pgsql的时候,总有些基础配置流程项目建立完之后后面就很少用,总是忘掉,写个文档记忆一下吧。基于net 6.0。
1.创建一个mvc项目和一个EF类库

2.在类库里面安装依赖dll
Microsoft.EntityFrameworkCore.Design
需要添加的相关依赖及说明如下:
- Npgsql.EntityFrameworkCore.PostgreSQL
 
PostgreSQL数据提供的支持EF Core的基础类库,是通过EF Core使用PostgreSQL数据库的根本。
- Npgsql.EntityFrameworkCore.PostgreSQL.Design
 
使用Guid(对应Postgre数据的类型为uuid)类型的主键必须,int/long类型的主键不添加也没问题。
- Microsoft.EntityFrameworkCore.Tools
 
EF Core工具,CodeFirst数据库迁移相关操作必须。
添加相关引用依赖的方式有多种,可以通过NuGet程序包管理器控制台的Install-Packege命令
PM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
PM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.Design
PM> Install-Package Microsoft.EntityFrameworkCore.Tools 
3.创建类和上下文
 public class College
 {
     public int CollegeId { get; set; }
     public string Name { get; set; }
     public List<Student> Students { get; set; }
 }
 public class Student
 {
     public int StudentId { get; set; }
     public string Name { get; set; }
     public int CollegeId { get; set; }
     public College College { get; set; }
 }
 
public class PostgreSQLContent : DbContext
{
    public PostgreSQLContent(DbContextOptions<PostgreSQLContent> options) : base(options)
    {
    }
    public DbSet<College> College { get; set; }
    public DbSet<Student> Student { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<College>()
          .HasMany(c => c.Students)
          .WithOne(s => s.College)
          .HasForeignKey(s => s.CollegeId);
    }
} 
4.在MVC项目里面配置数据库连接
5.使用 Add-Migration Inih 创建
6.Update-Database Inih 运行生成相应的数据库 。



















