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); } }
浙公网安备 33010602011771号