94 lines
2.9 KiB
C#
94 lines
2.9 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using SimpleTodoApiWithPg.Data;
|
|
using SimpleTodoApiWithPg.Models;
|
|
using Microsoft.AspNetCore.Http.HttpResults;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// === 配置 EF Core 连接 PostgreSQL ===
|
|
// 从配置中获取连接字符串
|
|
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
|
|
|
|
// 添加数据库上下文服务
|
|
builder.Services.AddDbContext<AppDbContext>(options =>
|
|
options.UseNpgsql(connectionString)); // 使用 Npgsql 作为 PostgreSQL 提供者
|
|
|
|
var app = builder.Build();
|
|
|
|
// === 应用数据库迁移 (仅在开发环境中推荐) ===
|
|
// 在应用启动时自动应用所有挂起的数据库迁移
|
|
using (var scope = app.Services.CreateScope())
|
|
{
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
dbContext.Database.Migrate();
|
|
}
|
|
|
|
// === 定义 API 端点 (Endpoints) ===
|
|
|
|
// GET /todos - 获取所有待办事项
|
|
app.MapGet("/todos", async (AppDbContext dbContext) =>
|
|
{
|
|
var todos = await dbContext.Todos.ToListAsync();
|
|
return TypedResults.Ok(todos);
|
|
});
|
|
|
|
// GET /todos/{id} - 根据 ID 获取单个待办事项
|
|
app.MapGet("/todos/{id}", async (int id, AppDbContext dbContext) =>
|
|
{
|
|
var todo = await dbContext.Todos.FindAsync(id);
|
|
return todo is not null
|
|
? TypedResults.Ok(todo)
|
|
: Results.NotFound($"待办事项 (ID: {id}) 不存在。");
|
|
});
|
|
|
|
// POST /todos - 新增一个待办事项
|
|
app.MapPost("/todos", async (Todo todo, AppDbContext dbContext) =>
|
|
{
|
|
// EF Core 会自动处理 ID 的生成(如果是自增主键)
|
|
dbContext.Todos.Add(todo);
|
|
await dbContext.SaveChangesAsync(); // 保存更改到数据库
|
|
|
|
// 回传 201 Created 并提供新资源的位置
|
|
return Results.Created($"/todos/{todo.Id}", todo);
|
|
});
|
|
|
|
// PUT /todos/{id} - 更新指定的待办事项
|
|
app.MapPut("/todos/{id}", async (int id, Todo inputTodo, AppDbContext dbContext) =>
|
|
{
|
|
// 查找现有待办事项
|
|
var existingTodo = await dbContext.Todos.FindAsync(id);
|
|
|
|
if (existingTodo is null)
|
|
{
|
|
return Results.NotFound($"待办事项 (ID: {id}) 不存在。");
|
|
}
|
|
|
|
// 更新属性
|
|
existingTodo.Title = inputTodo.Title;
|
|
existingTodo.IsCompleted = inputTodo.IsCompleted;
|
|
|
|
await dbContext.SaveChangesAsync(); // 保存更改到数据库
|
|
|
|
return Results.NoContent(); // 回传 204 No Content 表示成功但无内容回传
|
|
});
|
|
|
|
// DELETE /todos/{id} - 删除指定的待办事项
|
|
app.MapDelete("/todos/{id}", async (int id, AppDbContext dbContext) =>
|
|
{
|
|
var todoToDelete = await dbContext.Todos.FindAsync(id);
|
|
|
|
if (todoToDelete is null)
|
|
{
|
|
return Results.NotFound($"待办事项 (ID: {id}) 不存在。");
|
|
}
|
|
|
|
dbContext.Todos.Remove(todoToDelete);
|
|
await dbContext.SaveChangesAsync(); // 保存更改到数据库
|
|
|
|
return TypedResults.Ok($"待办事项 (ID: {id}) 已成功删除。");
|
|
});
|
|
|
|
// 运行应用程式
|
|
app.Run();
|