it
C# Entity Framework กับ Distributed System —

EF Core ใน Distributed System

Entity Framework Core เป็น ORM สำหรับ .NET เขียน Database Operations ด้วย C# Objects Distributed System หลาย Services หลาย Servers สื่อสารผ่าน Network
เนื้อหาเกี่ยวข้อง — NFS v4 Kerberos Multi-cloud Strategy
ใช้ EF Core กับ Microservices แต่ละ Service มี DbContext แยก Database per Service Domain Events สื่อสารระหว่าง Services
เนื้อหาเกี่ยวข้อง — ทำความเข้าใจ colocation hosting คือ

Distributed Patterns
// === Distributed Patterns ===
// 1. Outbox Message Processor (Background Service)
// public class OutboxProcessor : BackgroundService
// {
// protected override async Task ExecuteAsync(CancellationToken ct)
// {
// while (!ct.IsCancellationRequested)
// {
// using var scope = _services.CreateScope();
// var db = scope.ServiceProvider
// .GetRequiredService<OrderDbContext>();
//
// var messages = await db.OutboxMessages
// .Where(m => !m.IsProcessed)
// .OrderBy(m => m.CreatedAt)
// .Take(10)
// .ToListAsync(ct);
//
// foreach (var msg in messages)
// {
// await _messageBus.PublishAsync(msg.EventType, msg.Payload);
// msg.IsProcessed = true;
// msg.ProcessedAt = DateTime.UtcNow;
// }
//
// await db.SaveChangesAsync(ct);
// await Task.Delay(1000, ct);
// }
// }
// }
// 2. Saga Pattern — Distributed Transaction
// public class OrderSaga
// {
// public async Task Execute(CreateOrderCommand cmd)
// {
// // Step 1: Create Order (Order Service)
// var orderId = await _orderService.CreateOrder(cmd);
//
// try
// {
// // Step 2: Reserve Inventory (Inventory Service)
// await _inventoryService.ReserveItems(orderId, cmd.Items);
//
// // Step 3: Process Payment (Payment Service)
// await _paymentService.Charge(orderId, cmd.TotalAmount);
//
// // Step 4: Confirm Order
// await _orderService.ConfirmOrder(orderId);
// }
// catch (Exception)
// {
// // Compensating Transactions
// await _inventoryService.ReleaseItems(orderId);
// await _orderService.CancelOrder(orderId);
// throw;
// }
// }
// }
// 3. Distributed Caching with Redis
// builder.Services.AddStackExchangeRedisCache(options =>
// {
// options.Configuration = "localhost:6379";
// options.InstanceName = "OrderService_";
// });
//
// public class CachedOrderQuery
// {
// private readonly IDistributedCache _cache;
// private readonly OrderDbContext _db;
//
// public async Task<Order?> GetOrderAsync(Guid id)
// {
// var cacheKey = $"order:{id}";
// var cached = await _cache.GetStringAsync(cacheKey);
//
// if (cached != null)
// return JsonSerializer.Deserialize<Order>(cached);
//
// var order = await _db.Orders
// .Include(o => o.Items)
// .FirstOrDefaultAsync(o => o.Id == id);
//
// if (order != null)
// {
// await _cache.SetStringAsync(cacheKey,
// JsonSerializer.Serialize(order),
// new DistributedCacheEntryOptions
// {
// AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
// SlidingExpiration = TimeSpan.FromMinutes(2),
// });
// }
// return order;
// }
// }
// 4. Health Check
// builder.Services.AddHealthChecks()
// .AddDbContextCheck<OrderDbContext>("database")
// .AddRedis("localhost:6379", name: "redis")
// .AddRabbitMQ("amqp://localhost", name: "rabbitmq");
var patterns = new Dictionary<string, string>
{
["Outbox Pattern"] = "ส่ง Events อย่างน่าเชื่อถือ Atomically กับ DB",
["Saga Pattern"] = "Distributed Transactions ด้วย Compensating Actions",
["CQRS"] = "แยก Read/Write สำหรับ Scale แยกกัน",
["Distributed Cache"] = "Redis Cache ลด Database Load",
["Health Checks"] = "ตรวจสอบสถานะ Database, Redis, RabbitMQ",
};
Console.WriteLine("Distributed Patterns:");
foreach (var (pattern, desc) in patterns)
Console.WriteLine($" {pattern}: {desc}");
Best Practices
- Database per Service: แต่ละ Service มี Database แยก ไม่แชร์ข้าม Services
- Outbox Pattern: ใช้ Outbox ส่ง Events อย่างน่าเชื่อถือ Atomic กับ DB Write
- Concurrency: ใช้ Concurrency Token ป้องกัน Lost Updates
- Connection Pooling: ตั้ง MaxPoolSize เหมาะสม ไม่เปิด Connection ค้าง
- Retry Policy: ใช้ Polly สำหรับ Transient Fault Handling
- Migration: ใช้ EF Migrations จัดการ Schema Changes อัตโนมัติ
Entity Framework Core คืออะไร
ORM สำหรับ .NET เขียน Database Operations ด้วย C# Objects แทน SQL รองรับ SQL Server PostgreSQL MySQL SQLite Cosmos DB Migrations LINQ Change Tracking
แนะนำเพิ่มเติม — ติดตาม XM Signal
เนื้อหาเกี่ยวข้อง — บทความที่เกี่ยวข้อง: Strapi CMS Serverless Architecture





