XisongSpaceBooking_BackEnd/Program.cs
Chunyi 2be5694a6f 整合 Entity Framework Core 與 Pomelo MySQL
此次變更新增必要的命名空間,設置資料庫連接字串,並透過 `AddDbContext` 註冊 `ApplicationDbContext`。配置 MySQL 伺服器版本及相關選項,包括字符集和重試機制。根據開發環境啟用詳細錯誤和敏感數據日誌記錄,並添加控制台日誌記錄的過濾器。最後,應用程式被構建並運行。
2025-09-26 16:40:14 +08:00

46 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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