iT邦幫忙

2025 iThome 鐵人賽

0
佛心分享-IT 人自學之術

30 天從 Python 轉職場 C# 新手入門系列 第 29

Day29-CRUD API:用 Entity Framework Core 實作資料存取

  • 分享至 

  • xImage
  •  

前言

在上一篇文章中已經完成了 ASP.NET Core Web API 的架構與 Entity Framework Core 的基本設定。
今天,我們要實際實作最核心的部分 —— CRUD 操作 (Create, Read, Update, Delete)。那什麼是 CRUD?
CRUD 是資料操作的四個基本動作:

動作 英文 對應 HTTP 方法 說明
C Create POST 新增資料
R Read GET 讀取資料
U Update PUT / PATCH 更新資料
D Delete DELETE 刪除資料

透過 EF Core,我們可以使用 DbContext 直接操作資料庫,就像操作物件一樣。


建立 Model 與 DbContext

先建立一個簡單的模型,例如 Product(這邊跟前一篇的操作相同):

public class Product
{
    public int Id { get; set; }         // 主鍵
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

接著在 AppDbContext 中註冊它:

using Microsoft.EntityFrameworkCore;

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

    public DbSet<Product> Products => Set<Product>();
}

在 Program.cs 中注入資料庫:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseInMemoryDatabase("MyDb"));

這邊為了示範方便,使用了 InMemoryDatabase,但實際開發時可以改成 SQL Server、PostgreSQL 等適合自己的資料庫。

實作 Controller

建立一個 ProductsController:

dotnet add controller --name ProductsController --api

或手動建立 Controllers/ProductsController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

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

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

    // 🔹 1. 讀取全部資料 (GET)
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        return await _context.Products.ToListAsync();
    }

    // 🔹 2. 讀取單筆資料 (GET /id)
    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> GetProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null)
            return NotFound();

        return product;
    }

    // 🔹 3. 新增資料 (POST)
    [HttpPost]
    public async Task<ActionResult<Product>> PostProduct(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();

        // 回傳 201 Created
        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }

    // 🔹 4. 更新資料 (PUT)
    [HttpPut("{id}")]
    public async Task<IActionResult> PutProduct(int id, Product product)
    {
        if (id != product.Id)
            return BadRequest();

        _context.Entry(product).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        return NoContent();
    }

    // 🔹 5. 刪除資料 (DELETE)
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null)
            return NotFound();

        _context.Products.Remove(product);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}

測試 CRUD API

使用 curl、Postman 或 Swagger 測試:

✅ 建立資料 (POST)

POST /api/products
Content-Type: application/json

{
  "name": "Laptop",
  "price": 39900
}

✅ 查詢全部資料 (GET)

GET /api/products

✅ 查詢單筆資料 (GET /id)

GET /api/products/1

✅ 更新資料 (PUT)

PUT /api/products/1
Content-Type: application/json

{
  "id": 1,
  "name": "Gaming Laptop",
  "price": 45900
}

✅ 刪除資料 (DELETE)

DELETE /api/products/1

小結

今天完成了使用 Entity Framework Core 實作的完整 CRUD API!透過 EF Core,資料操作變得直觀又安全,結合 ASP.NET Core Web API,我們已經能快速開發出可用的後端服務。
本次的挑戰也到了尾聲了,下一篇文章就會是最後一篇總結了,雖然後半段有點落下進度,不過不知不覺也走到這邊了,繼續加油往最後一天挑戰邁進!!


上一篇
Day28-C#實體框架核心(Entity Framework Core)
系列文
30 天從 Python 轉職場 C# 新手入門29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言