| | | 1 | | using Elsa.Common.Entities; |
| | | 2 | | using Elsa.Common.Multitenancy; |
| | | 3 | | using Elsa.Tenants.Options; |
| | | 4 | | using Microsoft.EntityFrameworkCore.ChangeTracking; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Persistence.EFCore.EntityHandlers; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Represents a handler for applying the tenant ID to an entity before saving changes. |
| | | 11 | | /// </summary> |
| | 5526 | 12 | | public class ApplyTenantId(IOptions<TenantsOptions> tenantsOptions) : IEntitySavingHandler |
| | | 13 | | { |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public ValueTask HandleAsync(ElsaDbContextBase dbContext, EntityEntry entry, CancellationToken cancellationToken = d |
| | | 16 | | { |
| | | 17 | | // Only apply tenant ID if multitenancy is enabled |
| | 34902 | 18 | | if (!tenantsOptions.Value.IsEnabled) |
| | 0 | 19 | | return default; |
| | | 20 | | |
| | 34902 | 21 | | if (entry.Entity is not Entity entity) |
| | 0 | 22 | | return default; |
| | | 23 | | |
| | | 24 | | // Don't touch tenant-agnostic entities (marked with "*") |
| | 34902 | 25 | | if (entity.TenantId == Tenant.AgnosticTenantId) |
| | 0 | 26 | | return default; |
| | | 27 | | |
| | | 28 | | // Apply current tenant ID to entities without one |
| | 34902 | 29 | | if (entity.TenantId == null && dbContext.TenantId != null) |
| | 5810 | 30 | | entity.TenantId = dbContext.TenantId; |
| | | 31 | | |
| | 34902 | 32 | | return default; |
| | | 33 | | } |
| | | 34 | | } |