此次變更新增必要的命名空間,設置資料庫連接字串,並透過 `AddDbContext` 註冊 `ApplicationDbContext`。配置 MySQL 伺服器版本及相關選項,包括字符集和重試機制。根據開發環境啟用詳細錯誤和敏感數據日誌記錄,並添加控制台日誌記錄的過濾器。最後,應用程式被構建並運行。
46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using System;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||
using Microsoft.Extensions.Logging;
|
||
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
|
||
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
// 讀取連線字串
|
||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
|
||
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
||
|
||
// EF Core + Pomelo MySQL 註冊
|
||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||
{
|
||
var serverVersion = new MariaDbServerVersion(new Version(10, 6, 0));
|
||
|
||
options.UseMySql(connectionString, serverVersion, mySqlOptions =>
|
||
{
|
||
// 字元集設定
|
||
mySqlOptions.CharSet(CharSet.Utf8Mb4);
|
||
mySqlOptions.CharSetBehavior(CharSetBehavior.AppendToAllColumns);
|
||
// 可選:重試策略
|
||
mySqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
|
||
});
|
||
|
||
// 開發環境顯示更詳細的資料庫日誌
|
||
if (builder.Environment.IsDevelopment())
|
||
{
|
||
options.EnableDetailedErrors();
|
||
options.EnableSensitiveDataLogging();
|
||
options.LogTo(Console.WriteLine, LogLevel.Information, DbContextLoggerOptions.DefaultWithLocalTime);
|
||
}
|
||
});
|
||
|
||
// Logging(只在開發環境加強輸出 EF Core 訊息)
|
||
if (builder.Environment.IsDevelopment())
|
||
{
|
||
builder.Logging.AddConsole()
|
||
.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information)
|
||
.AddFilter("Microsoft.EntityFrameworkCore.Infrastructure", LogLevel.Information);
|
||
}
|
||
|
||
var app = builder.Build();
|
||
|
||
app.Run(); |