2. 前置條件與項目結構


3. 接口(Interface):藍圖設計

在 Repository 模式中,接口定義了對外的方法約定。以 IPokemonRepository 為例:

public interface IPokemonRepository
{
    bool CreatePokemon(int ownerId, int categoryId, Pokemon pokemon);
    bool Save(); // 返回布爾值,指示保存成功與否
    // … 其他方法如 Update、Delete、Get 等
}

要點:始終先定義接口,再在具體類中實現。接口扮演“藍圖”角色,有助于解耦與測試。

4. Repository 中的 Create 方法實現

4.1 處理多對多關系的數據預加載

由于 PokemonOwnerCategory 之間是多對多關系,插入新 Pokemon 時,必須先從數據庫中獲取對應的 OwnerCategory 實體:

var owner = _context.Owners.FirstOrDefault(o => o.Id == ownerId);
var category = _context.Categories.FirstOrDefault(c => c.Id == categoryId);

4.2 構造關聯實體并添加到 Join 表

接著,通過構造中間表實體,將它們與主實體關聯,并添加到相應的 DbSet:

var pokemonOwner = new PokemonOwner {
    Owner    = owner,
    Pokemon  = pokemon
};
var pokemonCategory = new PokemonCategory {
    Category = category,
    Pokemon  = pokemon
};

_context.PokemonOwners.Add(pokemonOwner);
_context.PokemonCategories.Add(pokemonCategory);

注意:若直接使用 AutoMapper 映射,邏輯會較為隱晦,這里手動創建對象更清晰易懂。

4.3 返回布爾值與統一保存邏輯

最后,執行保存并返回結果:

public bool CreatePokemon(int ownerId, int categoryId, Pokemon pokemon)
{
    // … 上述預加載與關聯構造
    _context.Pokemons.Add(pokemon);
    return Save();
}

public bool Save()
{
    // 建議改為 >0 更嚴謹:return _context.SaveChanges() > 0;
    return _context.SaveChanges() >= 0;
}


5. Controller 中的 POST 接口設計

5.1 從 Query 而非 Body 傳參的優勢

為了讓接口更加簡潔易讀,可將關聯實體的 Id(如 ownerIdcategoryId)通過 URL Query 傳遞,而將主要數據通過 Body 傳輸:

[HttpPost]
public IActionResult CreatePokemon(
    [FromQuery] int ownerId,
    [FromQuery] int categoryId,
    [FromBody] PokemonCreateDto dto)
{
    var pokemon = _mapper.Map < Pokemon > (dto);
    if (!_pokemonRepo.CreatePokemon(ownerId, categoryId, pokemon))
        return BadRequest("創建失敗");
    return NoContent(); // HTTP 204
}

5.2 DTO 與 AutoMapper 映射配置

定義精簡的 DTO,避免過度暴露數據庫結構:

public class PokemonCreateDto
{
    public string Name     { get; set; }
    public string ImageUrl { get; set; }
    // … 其他必要字段
}

MappingProfile 中添加映射規則:

CreateMap < PokemonCreateDto, Pokemon > ();

AutoMapper 會自動將 DTO 字段映射到實體,前提是名稱一致或已在 Profile 中自定義。


6. 測試與調試

  1. 使用 Swagger UI 或 Postman 發起 POST 請求:

    POST /api/pokemons?ownerId=1&categoryId=2
    Body: { "name": "Mew", "imageUrl": "…" }
  2. 確認 HTTP 204 返回,無 Content:

  1. 檢查數據庫中 PokemonsPokemonOwnersPokemonCategories 表,驗證數據是否正確插入。

7. 小結與最佳實踐

通過以上步驟,您已掌握在 .NET Core 中使用 Entity Framework Core 實現復雜 Create API 的核心方法,并能編寫出結構清晰、性能可控、易于維護的 RESTful 接口。
希望這篇教程能助您在 API 開發道路上走得更穩、更遠!

原文引自YouTube視頻:https://www.youtube.com/watch?v=j0-cnsCZf7g

上一篇:

微信API接口調用憑證+Access token泄露

下一篇:

ASP.NET Core Web API DELETE 請求實戰|Repository 模式下的刪除操作詳解
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費