From 7b5c601821e50eb68a7b7eaffda2aac4fce86c92 Mon Sep 17 00:00:00 2001 From: Leonid Pershin Date: Fri, 24 Jul 2026 21:14:26 +0300 Subject: [PATCH] Configure entity key generation in AppDbContext: set Guid keys for domain entities to never be generated by EF, preventing unintended updates during child entity additions. --- .../Persistence/AppDbContext.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/backend/src/TeleWave.Infrastructure/Persistence/AppDbContext.cs b/backend/src/TeleWave.Infrastructure/Persistence/AppDbContext.cs index 3475ebe..0035820 100644 --- a/backend/src/TeleWave.Infrastructure/Persistence/AppDbContext.cs +++ b/backend/src/TeleWave.Infrastructure/Persistence/AppDbContext.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; using TeleWave.Application.Common.Interfaces; using TeleWave.Domain.Auth; using TeleWave.Domain.Broadcast; @@ -27,5 +28,21 @@ public class AppDbContext(DbContextOptions options) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); + + // Guid-ключи доменных сущностей мы задаём сами в фабриках. Без этого EF считает выставленный + // ключ признаком уже существующей строки и при добавлении дочерней сущности через коллекцию + // отслеживаемого родителя (напр. show.AddEpisode) делает UPDATE вместо INSERT → «affected 0». + foreach (var entityType in modelBuilder.Model.GetEntityTypes()) + { + if ( + entityType.ClrType.Namespace?.StartsWith("TeleWave.Domain", StringComparison.Ordinal) + != true + ) + continue; + + var idProperty = entityType.FindProperty("Id"); + if (idProperty is not null && idProperty.ClrType == typeof(Guid)) + idProperty.ValueGenerated = ValueGenerated.Never; + } } }