| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using Elsa.Common.Entities; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.EntityFrameworkCore.Metadata; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Persistence.EFCore.EntityHandlers; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Represents a class that applies a filter to set the TenantId for entities. |
| | | 10 | | /// </summary> |
| | | 11 | | public class SetTenantIdFilter : IEntityModelCreatingHandler |
| | | 12 | | { |
| | | 13 | | /// <inheritdoc /> |
| | | 14 | | public void Handle(ElsaDbContextBase dbContext, ModelBuilder modelBuilder, IMutableEntityType entityType) |
| | | 15 | | { |
| | 0 | 16 | | if (!typeof(Entity).IsAssignableFrom(entityType.ClrType)) |
| | 0 | 17 | | return; |
| | | 18 | | |
| | 0 | 19 | | modelBuilder |
| | 0 | 20 | | .Entity(entityType.ClrType) |
| | 0 | 21 | | .HasQueryFilter(CreateTenantFilterExpression(dbContext, entityType.ClrType)); |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | private LambdaExpression CreateTenantFilterExpression(ElsaDbContextBase dbContext, Type clrType) |
| | | 25 | | { |
| | 0 | 26 | | var parameter = Expression.Parameter(clrType, "e"); |
| | | 27 | | |
| | | 28 | | // e => EF.Property<string>(e, "TenantId") == this.TenantId |
| | 0 | 29 | | var tenantIdProperty = Expression.Call( |
| | 0 | 30 | | typeof(EF), |
| | 0 | 31 | | nameof(EF.Property), |
| | 0 | 32 | | [typeof(string)], |
| | 0 | 33 | | parameter, |
| | 0 | 34 | | Expression.Constant("TenantId")); |
| | | 35 | | |
| | 0 | 36 | | var tenantIdOnContext = Expression.Property( |
| | 0 | 37 | | Expression.Constant(dbContext), |
| | 0 | 38 | | nameof(ElsaDbContextBase.TenantId)); |
| | | 39 | | |
| | 0 | 40 | | var body = Expression.Equal(tenantIdProperty, tenantIdOnContext); |
| | | 41 | | |
| | 0 | 42 | | return Expression.Lambda(body, parameter); |
| | | 43 | | } |
| | | 44 | | } |