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 @   胸怀丶若谷  阅读(716)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
历史上的今天:
2020-10-09 bash: pip3:未找到命令
2020-10-09 Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-4_w0c665/PyQt5/
点击右上角即可分享
微信分享提示

目录导航