博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

net core中结合EntityFrameworkCore的DB first使用PostgreSQL

Posted on 2025-09-03 16:24  火冰·瓶  阅读(4)  评论(0)    收藏  举报

一、安装 NuGet 包

Microsoft.EntityFrameworkCore
Npgsql.EntityFrameworkCore.PostgreSQL
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools

 

二、创建模型类

public class Employee
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public string? Department { get; set; }
    public DateTime? CreatedAt { get; set; }
}

 

三、创建 DbContext

using Microsoft.EntityFrameworkCore;

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

    public DbSet<Employee> Employees { get; set; }
}

 

四、配置连接字符串(appsettings.json)

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Port=5432;Database=your_db;Username=your_user;Password=your_password"
  }
}

 

五、注册服务(Program.cs)

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

 

六、创建数据库迁移

dotnet ef migrations add InitialCreate     ##InitialCreate是自定义的名称
dotnet ef database update

 

七、控制器中使用

[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
    private readonly AppDbContext _context;

    public EmployeeController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var employees = await _context.Employees.ToListAsync();
        return Ok(employees);
    }

    [HttpPost]
    public async Task<IActionResult> Create(Employee employee)
    {
        _context.Employees.Add(employee);
        await _context.SaveChangesAsync();
        return CreatedAtAction(nameof(GetAll), new { id = employee.Id }, employee);
    }
}