From 2be5694a6f3b41c3c4f38b4f1fb2b16dd2561312 Mon Sep 17 00:00:00 2001 From: Chunyi Date: Fri, 26 Sep 2025 16:40:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B4=E5=90=88=20Entity=20Framework=20Core?= =?UTF-8?q?=20=E8=88=87=20Pomelo=20MySQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此次變更新增必要的命名空間,設置資料庫連接字串,並透過 `AddDbContext` 註冊 `ApplicationDbContext`。配置 MySQL 伺服器版本及相關選項,包括字符集和重試機制。根據開發環境啟用詳細錯誤和敏感數據日誌記錄,並添加控制台日誌記錄的過濾器。最後,應用程式被構建並運行。 --- Program.cs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Program.cs diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..fce92ad --- /dev/null +++ b/Program.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Logging; +using Pomelo.EntityFrameworkCore.MySql.Infrastructure; + +var builder = WebApplication.CreateBuilder(args); + +// Ūsur +var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") + ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); + +// EF Core + Pomelo MySQL U +builder.Services.AddDbContext(options => +{ + var serverVersion = new MariaDbServerVersion(new Version(10, 6, 0)); + + options.UseMySql(connectionString, serverVersion, mySqlOptions => + { + // r]w + mySqlOptions.CharSet(CharSet.Utf8Mb4); + mySqlOptions.CharSetBehavior(CharSetBehavior.AppendToAllColumns); + // iGյ + mySqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null); + }); + + // }oܧԲӪƮwx + if (builder.Environment.IsDevelopment()) + { + options.EnableDetailedErrors(); + options.EnableSensitiveDataLogging(); + options.LogTo(Console.WriteLine, LogLevel.Information, DbContextLoggerOptions.DefaultWithLocalTime); + } +}); + +// Logging]ub}oҥ[jX EF Core T^ +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(); \ No newline at end of file