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(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();