asp.net core web api model naming rule coding style appsettings visual studio code restful api

ASP.NET Core 5 EP 7:定義資料的Model

資料模型(Model)的用意

當我們在開發API時,就像開發一個開放的函數,讓需求者能呼叫API,並透過具標準規格的通訊協定與輸入資料來取得答案,而API本身在存取資料庫時,也盡可能的定義資料結構去簡化操作,此時,定義資料模型(Model)就非常的重要!

PS:接下來,我們就稱資料模型為Model。

定義Model

設計Model的思考方向是食譜(名稱、描述、烹煮時間、食材、調味料)以及份量(名稱、單位、重量),其中,食材與調味料為份量的陣列,代表食材與調味料都可以放入多個項目,假設以糖醋排骨為例,有2種食材、3種調味料,其結構如下:

{
  "Id": "A0001",
  "Name": "糖醋排骨",
  "Description": "一種酸酸甜甜的排骨料理",
  "CookingTime": 30,
  "Ingredients": 
   [
    {"Name": "排骨", "Unit": "公斤", "Weight": 1},
    {"Name": "彩椒", "Unit": "個", "Weight": 2}
   ],
  "Seasonings": 
   [
    {"Name": "糖", "Unit": "公克", "Weight": 30},
    {"Name": "醋", "Unit": "匙", "Weight": 5},
    {"Name": "番茄醬", "Unit": "匙", "Weight": 10 }
   ]
}

基於上述的想法,我們至少需要定義兩種Model,在Models目錄下,分別新增兩個檔案(class):Resipe.cs與Dosage.cs,分別是用於定義食材份量與食譜內容的Model:

Resipe.cs

using System.ComponentModel.DataAnnotations;

namespace CookbookApi.Models
{
    public class Resipe
    {
        // Required表示這是一個不能被遺漏掉的資料
        [Required]
        // 定義字串長度為5個字元
        [StringLength(5)]
        public string Id {set;get;}

        [Required]
        [StringLength(20, MinimumLength = 3)]
        public string Name { set; get; }

        [Required]
        [StringLength(100, MinimumLength = 5)]
        public string Description { set; get; }

        [Required]
        // 可以用正則表達式(Regex Tester)檢查輸入的內容
        [RegularExpression(@"\d{1,3}")]
        public int CookingTime { set; get; }

        [Required]
        // 以其他Model來定義另一個Model,屆時可以將資料組合在一起
        public Models.Dosage[] Ingredients { set; get; }

        [Required]
        public Models.Dosage[] Seasonings { set; get; }
    }
}

Dosage.cs

using System.ComponentModel.DataAnnotations;

namespace CookbookApi.Models
{
    public class Dosage
    {
        // Required標籤表示這個欄位是必填
        [Required]
        // 定義字串最長20字元,最短5字元
        [StringLength(20, MinimumLength = 1)]
        public string Name {set;get;}

        [Required]
        [StringLength(20, MinimumLength = 1)]
        public string Unit {set;get;}

        [Required]
        public int Weight {set;get;}
    }
}

以上就完成了Models的定義,接下來,我們試著把資料塞進去!

~ END ~


, ,

Related posts

Latest posts