iT邦幫忙

2025 iThome 鐵人賽

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

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

Day28-C#實體框架核心(Entity Framework Core)

  • 分享至 

  • xImage
  •  

前言

在前面的幾天,我們學會了如何建立 Web API、設定 Routing 與 Controller,但目前的 API 還只是「靜態」的,資料都寫死在程式裡。今天要引入的主角 —— Entity Framework Core (EF Core),可以讓我們透過 C# 物件直接操作資料庫,不用手寫繁瑣的 SQL!
想像 EF Core 就像一個「中譯員」,它會幫你把 C# 類別(Class)翻譯成資料庫的表格(Table),同時也能幫你把 SQL 查詢結果轉回物件。


什麼是 Entity Framework Core?

Entity Framework Core(簡稱 EF Core) 是微軟推出的 ORM(Object Relational Mapper) 框架。
簡單來說,它能讓你用「物件導向」的方式與資料庫互動,而不是直接寫 SQL。

傳統方式 使用 EF Core
SELECT * FROM Products WHERE Id = 1; context.Products.First(p => p.Id == 1);
INSERT INTO Products (Name, Price) VALUES ('Pen', 10) context.Products.Add(new Product {...}); context.SaveChanges();

建立專案並安裝 EF Core 套件

接下來的步驟與範例會以之前Day25的文章為基底來做後續的操作,所以如果想跟著一起做的可以回頭參考,建立起專案。

安裝主要套件

打開終端機(或 Visual Studio Code 的 Terminal),輸入以下指令:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools

這裡是選擇 SQLite 作為練習用資料庫,因為它輕量又不需額外安裝,之後要換成 SQL Server、PostgreSQL 也只要改掉連線字串與 provider。

建立資料模型 (Model)

假設今天要建立一個簡單的「商品管理系統」,先建立一個 Models 資料夾,並新增 Product.cs:

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

當中每一個屬性會對應到資料庫中的一個欄位。

建立資料庫上下文 (DbContext)

EF Core 的核心概念是 DbContext,它就像是「資料庫的入口」,負責追蹤、查詢與更新資料。建立一個 Data 資料夾,新增 AppDbContext.cs:

using Microsoft.EntityFrameworkCore;
using MyApi.Models;

namespace MyApi.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options) { }

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

DbSet<Product> 表示我們要在資料庫中建立一個「Products」的資料表。

設定連線字串與註冊 DbContext

開啟 appsettings.json,加入 SQLite 的連線設定:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=products.db"
  }
}

接著在 Program.cs 註冊 EF Core:

using Microsoft.EntityFrameworkCore;
using MyApi.Data;

var builder = WebApplication.CreateBuilder(args);

// 註冊 DbContext
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.MapControllers();
app.Run();

建立資料庫(Migration)

Migration 是 EF Core 幫你「從程式碼建立資料庫結構」的工具。
執行以下指令:

dotnet ef migrations add InitialCreate
dotnet ef database update

執行後,資料夾中會出現一個 Migrations 資料夾,並且會生成一個 products.db SQLite 檔案。

在 Controller 中使用 EF Core

建立 Controllers/ProductsController.cs:

using Microsoft.AspNetCore.Mvc;
using MyApi.Data;
using MyApi.Models;

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

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

        [HttpGet]
        public ActionResult<IEnumerable<Product>> GetAll()
        {
            return _context.Products.ToList();
        }

        [HttpGet("{id}")]
        public ActionResult<Product> GetById(int id)
        {
            var product = _context.Products.Find(id);
            if (product == null)
                return NotFound();
            return product;
        }

        [HttpPost]
        public IActionResult Create(Product product)
        {
            _context.Products.Add(product);
            _context.SaveChanges();
            return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
        }
    }
}

這樣就能透過:

  • GET /api/products → 取得所有商品
  • POST /api/products → 新增商品
  • GET /api/products/{id} → 取得單一商品

測試結果

在終端機輸入:

dotnet run

接著使用 Postman 或瀏覽器測試:

GET https://localhost:7285/api/products

POST https://localhost:7285/api/products
JSON 內容:

{
  "name": "Notebook",
  "price": 35.5
}

這樣就完成了一個連接資料庫的簡單 Web API了!


結語

今天學到的 EF Core 是所有企業級開發的基礎之一,有了它, API 就不再只是回傳固定文字,而是能真正「連動資料庫」,可以做的想要的查詢甚至是新增了。明天學習的內容是CRUD API,本次的鐵人賽也即將進入尾聲(昨天意外沒有在時間內發布文章嗚嗚嗚,但我還是會努力把30天都完成的!!)


上一篇
Day27-Model 與 DTO(ASP.NET Core Web API 教學)
下一篇
Day29-CRUD API:用 Entity Framework Core 實作資料存取
系列文
30 天從 Python 轉職場 C# 新手入門29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言