ASP .Net Core: 使用EF连接postgresql

备注

关于数据库的创建,可参考下方的链接,去创建测试环境,我已经有现成的数据库,故不再记录创建数据库的过程。

实现步骤

安装EF工具

dotnet tool install --global dotnet-ef

安装其他依赖

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools

添加数据连接信息

"ConnectionStrings": {
    "WebApiDatabase": "Host=[]; Database=[]; Username=[]; Password=[]"
  },

需要注意的是,我隐藏了自己的配置信息,请将[]替换为自己的内容

文件目录导览

image

创建一个Data文件夹,并创建ApiDbContext

using Microsoft.EntityFrameworkCore;

namespace DbExploration.Data;

public class ApiDbContext : DbContext
{
    public ApiDbContext(DbContextOptions<ApiDbContext> options):base(options) {  }
}

在program.cs文件中添加配置

builder.Services.AddEntityFrameworkNpgsql().AddDbContext<ApiDbContext>(opt =>
    opt.UseNpgsql(builder.Configuration.GetConnectionString("WebApiDatabase")));

image

新增Models文件夹,创建BaseEntity泛型类

public abstract class BaseEntity
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public DateTime UpdatedDate { get; set; } = DateTime.UtcNow;
    public string UpdatedBy { get; set; } = "";
    public string AddedBy { get; set; } = "";
    public DateTime AddedDate { get; set; } = DateTime.UtcNow;
    public int Status { get; set; } = 1;
}

创建模型

创建Team模型

public class Team : BaseEntity
{
    public Team()
    {
        Drivers = new HashSet<Driver>();
    }

    public string Name { get; set; } = "";
    public string Year { get; set; } = "";

    public virtual ICollection<Driver> Drivers { get; set; }
}

创建Driver模型

public class Driver: BaseEntity
{
    public Guid TeamId { get; set; }
    public string Name { get; set; } = "";
    public int RacingNumber { get; set; } 
    public virtual Team Team { get; set; }
    public virtual DriverMedia DriverMedia { get; set; }
}

创建DriverMedia模型

public class DriverMedia
{
    public int Id { get; set; }
    public byte[] Media { get; set; }
    public string Caption { get; set; }

    public Guid DriverId { get; set; }
    public Driver Driver { get; set; }
}

更新ApiDbContext中的内容

public class ApiDbContext : DbContext
{
    public virtual DbSet<Driver> Drivers { get; set; }
    public virtual DbSet<Team> Teams { get; set; }

    public ApiDbContext(DbContextOptions<ApiDbContext> options):base(options) {  }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);


        modelBuilder.Entity<Driver>(entity =>
        {
            // One to Many relationship
            entity.HasOne(d => d.Team)
                .WithMany(p => p.Drivers)
                .HasForeignKey(d => d.TeamId)
                .OnDelete(DeleteBehavior.Restrict)
                .HasConstraintName("FK_Driver_Team");

            // One to One
            entity.HasOne(d => d.DriverMedia)
                .WithOne(i => i.Driver)
                .HasForeignKey<DriverMedia>(b => b.DriverId);
        });


    }
}

原文中的内容有bug,直接复制我的内容即可。

执行建表指令

dotnet ef migrations add "initial_migrations"
dotnet ef database update

运行结果展示

执行dotnet ef database update后,显示下图信息,则表示运行成功

image

数据库中也有新增的表
image

至此大功告成!

参考链接

https://dev.to/moe23/net-6-with-postgresql-576a

posted @ 2023-10-09 13:43  胸怀丶若谷  阅读(612)  评论(0编辑  收藏  举报