
HTTP API vs WebSocket API:選擇哪個來實現實時通信?
PokemonReview
并確認,即完成數據庫創建。將此字符串粘入 appsettings.json
中:
{
"ConnectionStrings": {
"DefaultConnection": " < Your_Connection_String_Here > "
}
}
此法避免繁瑣手動拼接,幾秒即可拿到正確格式。
在 VS Code 的 NuGet Package Manager 中,搜索并安裝:
Microsoft.EntityFrameworkCore.SqlServer
(核心數據庫提供者)Microsoft.EntityFrameworkCore.Design
(設計時支持)確保選用 Latest Stable 版本,并在 .csproj
中見到對應 < PackageReference >
條目。
DataContext
并注冊實體集合新建 Data/DataContext.cs
,繼承自 DbContext
:
public class DataContext : DbContext
{
public DataContext(DbContextOptions < DataContext > options)
: base(options) { }
public DbSet < Pokemon > Pokemons { get; set; }
public DbSet < Owner > Owners { get; set; }
public DbSet < PokemonOwner > PokemonOwners { get; set; }
/* … 其他 DbSet … */
}
DbSet < T >
屬性名稱應 “復數” 以符合 EF 約定。OnModelCreating
配置多對多關系protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Pokemon ←→ Category 多對多
modelBuilder.Entity < PokemonCategory > ()
.HasKey(pc = > new { pc.PokemonId, pc.CategoryId });
modelBuilder.Entity < PokemonCategory > ()
.HasOne(pc = > pc.Pokemon)
.WithMany(p = > p.PokemonCategories)
.HasForeignKey(pc = > pc.PokemonId);
modelBuilder.Entity < PokemonCategory > ()
.HasOne(pc = > pc.Category)
.WithMany(c = > c.PokemonCategories)
.HasForeignKey(pc = > pc.CategoryId);
// 同理配置 PokemonOwner 多對多...
}
通過 Fluent API 明確聲明聯合主鍵與雙向導航,使 EF Core 正確生成中間表。
Program.cs
注冊 DbContext
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext < DataContext > (options = >
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
將 DataContext
注入 DI 容器,即可在控制器、倉儲中通過構造注入使用。
在 Package Manager Console 或 CLI 中運行:
dotnet ef migrations add InitialCreate
dotnet ef database update
add
生成遷移代碼;update
將表結構同步到 SQL Server。SeedService.cs
,編寫 SeedDataAsync(DataContext ctx)
,往 DbContext
中添加初始實體并調用 SaveChangesAsync()
。在 Program.cs
注入并調用:
builder.Services.AddTransient < SeedService > ();
var app = builder.Build();
await app.Services.GetRequiredService < SeedService > ().SeedDataAsync();
dotnet run
,檢查數據庫中是否已有示例數據。DbContext
→ 配置關系 → 注冊 DI → 執行 Migrations → Seed。原文引自YouTube視頻:https://www.youtube.com/watch?v=EmV_IBYIlyo