練習 - 新增資料存放區

已完成

在開始針對披薩實作 Web API 之前,您需要有供執行作業的資料存放區。

您需要 model 類別來代表庫存中的披薩。 模型包含代表披薩特性的屬性。 模型會用來在 Web API 中傳遞資料,以及用來將披薩選項保存在資料存放區中。

在本單元中,該資料存放區是簡單的本機記憶體內部快取服務。 在真實世界的應用程式中,您會考慮使用資料庫 (例如 SQL Server) 搭配 Entity Framework Core。

建立披薩模型

  1. 執行下列命令來建立 Models 資料夾:

    mkdir Models
    

    在 Visual Studio Code 中選取 Models 資料夾,並新增名為 Pizza.cs 的新檔案。

    Screenshot of adding a new file to the Models folder in Visual Studio Code.

    專案根目錄現在包含 Models 目錄,裡面有一個空的 Pizza.cs 檔案。 目錄名稱 Models 是慣例。 此目錄名稱來自 Web API 使用的模型-檢視-控制器架構。

  2. 將下列程式碼新增至 Models/Pizza.cs,然後儲存您的變更。 這個類別會定義披薩。

    namespace ContosoPizza.Models;
    
    public class Pizza
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public bool IsGlutenFree { get; set; }
    }
    

新增資料服務

  1. 執行下列命令來建立 Services 資料夾:

    mkdir Services
    

    在 Visual Studio Code 中選取該資料夾,並新增名為 PizzaService.cs 的新檔案。

    Screenshot of Visual Studio Code that shows adding a new file to the Services folder.

  2. 將下列程式碼新增至 Services/PizzaService.cs,然後儲存您的變更。 此程式碼會建立記憶體內部披薩資料服務。

    using ContosoPizza.Models;
    
    namespace ContosoPizza.Services;
    
    public static class PizzaService
    {
        static List<Pizza> Pizzas { get; }
        static int nextId = 3;
        static PizzaService()
        {
            Pizzas = new List<Pizza>
            {
                new Pizza { Id = 1, Name = "Classic Italian", IsGlutenFree = false },
                new Pizza { Id = 2, Name = "Veggie", IsGlutenFree = true }
            };
        }
    
        public static List<Pizza> GetAll() => Pizzas;
    
        public static Pizza? Get(int id) => Pizzas.FirstOrDefault(p => p.Id == id);
    
        public static void Add(Pizza pizza)
        {
            pizza.Id = nextId++;
            Pizzas.Add(pizza);
        }
    
        public static void Delete(int id)
        {
            var pizza = Get(id);
            if(pizza is null)
                return;
    
            Pizzas.Remove(pizza);
        }
    
        public static void Update(Pizza pizza)
        {
            var index = Pizzas.FindIndex(p => p.Id == pizza.Id);
            if(index == -1)
                return;
    
            Pizzas[index] = pizza;
        }
    }
    

    此服務提供簡單的記憶體內部資料快取服務,預設有兩個披薩。 我們的 Web API 使用該服務做示範。 當我們停止並啟動 Web API 時,記憶體內部資料快取會從 PizzaService 的建構函式重設為兩個預設披薩。

建置 Web API 專案

執行下列命令以建置應用程式:

dotnet build

建置成功且沒有顯示任何警告。 如果建置失敗,請檢查輸出以取得疑難排解資訊。

在下一個單元中,您將建立控制器來使用 Pizza 模型和 PizzaService 類別。