首先需要安裝.NET SDK 6.0 下載地址:Download .NET 6.0 (Linux, macOS, and Windows) (microsoft.com)
在VS Code終端運行指令創建項目
進入項目所在的文件夾
cd test
重啟VS Code
code -r ../test

以上步驟結束后,下面就可以開始進行開發了。
新建Models文件夾
mkdir Models
在Models文件夾下添加實體類 UserModel.cs
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace test.Models; [Table("User")] public class UserModel { [Key] public long ID { get; set; } [Required] [MaxLength(50)] [Column("UserName")] public string? UserName { get; set; } }
新建數據庫上下文 TestDbContext.cs
using Microsoft.EntityFrameworkCore; using test.Models; namespace test; public class TestDbContext : DbContext { public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } public DbSet<UserModel> UserModels { get; set; } = null!; }
在Program.cs中進行依賴注入
builder.Services.AddDbContext<TestDbContext>(opt => opt.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Test;MultipleActiveResultSets=true;Trusted_Connection=True;"));
在終端執行以下指令,自動生成Controller
dotnet aspnet-codegenerator controller -name UserController -async -api -m UserModel -dc TestDbContext -outDir Controllers

可以看到,此時項目里的Controllers文件夾下自動生成了 UserController.cs 文件,里面自動生成了基本的增刪改查方法。
執行以下指令,自動生成數據庫
dotnet ef migrations add InitialCreate
dotnet ef database update

成功后,運行項目。
dotnet watch run
此時會自動彈出swagger頁面

可以開始測試了。
以上就是全部內容。
參考微軟官方教程:教程:使用 ASP.NET Core 創建 Web API | Microsoft Docs
