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.
This commit is contained in:
@@ -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<AppDbContext> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user