事前準備
- 安裝 VS code, dbeaver, docker desktop
- 安裝 .net 6 sdk & run time
- docker 安裝 mysql & 建立一個 table ex: Books
參考資料: https://ithelp.ithome.com.tw/articles/10272193

4. 安裝 dotnet tool
# dotnet ef
dotnet 工具安裝 --global dotnet-ef
dotnet 工具更新 --global dotnet-ef
# dotnet-aspnet-codegenerator
dotnet 工具安裝-g dotnet-aspnet-codegenerator
dotnet 工具更新-g dotnet-aspnet-codegenerator
dotnet 工具列表-g # 查看包(全城)

開始建立專案
- 建專案的目錄:~/Projects
- 專案名稱:BookApi
- 連線字串:”server=localhost;Port=3306;Database=Joe;User=DevAuth;Password=Dev127336;”
# 切到專案目錄
cd ~/Projects
# 建立解決方案
dotnet new sln -o BookApi
cd BookApi
# 建立資料夾
mkdir BookApi
cd BookApi
# 建立 web api -f || --framework
dotnet new webapi -f net6.0
# ef core
dotnet add package Microsoft.EntityFrameworkCore
# mysql provider
dotnet add package Pomelo.EntityFrameworkCore.MySql
# dotnet-ef cli 的依賴
dotnet add package Microsoft.EntityFrameworkCore.Design
# dotnet-aspnet-codegenerator cli 的依賴
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 6.0 # 最新版我的環境裝不過 所以裝v6
# dbcontext scaffold -o 產生的包裝的目錄 -c dbcontext -f 強制
dotnet ef dbcontext scaffold "server=localhost;Port=3306;Database=Joe; User=DevAuth;Password=Dev127336;" "Pomelo.EntityFrameworkCore.MySql" -o ./Models -c DataContext -f
# 產生 controller
dotnet aspnet-codegenerator controller --controllerName BookController -async -api -actions -m Book -dc DataContext -outDir Controllers -f
dotnet sln add Bookapi # 跑好之後 可以順便把專案 加入到解決方案裡面
cat BookApi.sln # 看一下 可以看到我們的 BookApi 專案

# 切到專案內
cd BookApi
# git
git init
dotnet new gitignore
git add .
git commit -m 'first commit'
# vs code 開啟
code .

先把用不到的檔案刪掉
rm WeatherForecast.cs
rm WeatherForecastController
rm -r Data # Dbcontext 我們在 Models目錄底下 dotnet ef dbcontext scaffold 已經有幫我們產生好了
接下來 還有一些調整
Models/DataContext.cs
- override OnCofiguring 設定連線資訊
- _configuration.GetConnectionString 可以拿到 appsetting 設定檔
- override OnModelCreating 會對應資料庫設定

appsetting.json 設定檔

Program.cs
sql server 連線設定是 code generator 預設幫我們設定的 我們可以把 DbContextOptionsBuilder這段刪掉 然後要 using BookApi.Models;

Controllers/BookController.cs
這裡出現了很多報錯 是因為 dbset 沒有跟我們dbcontext 對應上加上s就好了


dotnet build # 建置
dotnet run # 運行

在 swagger/index.html 目錄下 就會有預設的 swagger 可以測試api 囉!
.net 6幫我設定好 swagger 真的很方便,就不用再自己開 postman 打 api
