| | | 1 | | namespace Nabs.Persistence; |
| | | 2 | | |
| | | 3 | | public abstract class TenantableDbContext<TTenantEntity>( |
| | | 4 | | DbContextOptions options, |
| | | 5 | | IApplicationContext applicationContext) |
| | 1 | 6 | | : DbContext(options), ITenantableDbContext |
| | | 7 | | where TTenantEntity : class, ITenantEntity |
| | | 8 | | { |
| | 1 | 9 | | public IApplicationContext ApplicationContext { get; } = applicationContext; |
| | | 10 | | |
| | 1 | 11 | | public DbSet<TTenantEntity> Tenants => Set<TTenantEntity>(); |
| | | 12 | | |
| | | 13 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | | 14 | | { |
| | 1 | 15 | | base.OnModelCreating(modelBuilder); |
| | | 16 | | |
| | 3 | 17 | | foreach (var entityType in modelBuilder.Model.GetEntityTypes()) |
| | | 18 | | { |
| | 1 | 19 | | if (typeof(ITenantableEntity).IsAssignableFrom(entityType.ClrType)) |
| | | 20 | | { |
| | 1 | 21 | | entityType.AddTenantEntityQueryFilter(this); |
| | | 22 | | } |
| | | 23 | | |
| | 1 | 24 | | if (typeof(TTenantEntity) == entityType.ClrType) |
| | | 25 | | { |
| | 1 | 26 | | Expression<Func<TTenantEntity, bool>> filter = entity => |
| | 1 | 27 | | EF.Property<Guid>(entity, "Id") == ApplicationContext.TenantContext.TenantId; |
| | | 28 | | |
| | 1 | 29 | | entityType.SetQueryFilter(filter); |
| | | 30 | | } |
| | | 31 | | } |
| | 1 | 32 | | } |
| | | 33 | | |
| | | 34 | | public override int SaveChanges() |
| | | 35 | | { |
| | 1 | 36 | | SetTenantId(); |
| | 1 | 37 | | return base.SaveChanges(); |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) |
| | | 41 | | { |
| | 1 | 42 | | SetTenantId(); |
| | 1 | 43 | | return await base.SaveChangesAsync(cancellationToken); |
| | 1 | 44 | | } |
| | | 45 | | |
| | | 46 | | private void SetTenantId() |
| | | 47 | | { |
| | 1 | 48 | | var entries = ChangeTracker.Entries() |
| | 2 | 49 | | .Where(e => e.Entity is ITenantableEntity && |
| | 2 | 50 | | e.State == EntityState.Added || |
| | 2 | 51 | | e.State == EntityState.Modified); |
| | 1 | 52 | | if (entries.Any()) |
| | | 53 | | { |
| | 1 | 54 | | if (ApplicationContext.TenantContext.TenantId == Guid.Empty) |
| | | 55 | | { |
| | 1 | 56 | | throw new InvalidOperationException("TenantId is not set."); |
| | | 57 | | } |
| | | 58 | | } |
| | | 59 | | |
| | 3 | 60 | | foreach (var entry in entries) |
| | | 61 | | { |
| | 1 | 62 | | entry.Property(nameof(TenantId)).CurrentValue = ApplicationContext.TenantContext.TenantId; |
| | | 63 | | } |
| | 1 | 64 | | } |
| | | 65 | | } |