零框架多租户设计方案

This commit is contained in:
administrator committed 2024-04-28 16:00:15 +08:00
1 parent b7caaa2d0c
commit b4a704526d
42 files changed
+1002 -1

No files matched your search

@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore;
using MultiTenancySample.FieldIsolationService.Entities;
using MultiTenancySample.ServiceDefaults;
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
{
public class DataSeeding(IDbContextFactory<FieldIsolationServiceDbContext> dbContext, ICurrentTenant currentTenant)
{
public async Task SeedDataAsync()
{
currentTenant.SetTenant("Tenant1");
FieldIsolationServiceDbContext dbContext1 = await dbContext.CreateDbContextAsync();
if (await dbContext1.Database.EnsureCreatedAsync())
{
await dbContext1.AddRangeAsync(new List<Product> {
new() { Id = Guid.NewGuid(), Name = "Product1"},
new() { Id = Guid.NewGuid(), Name = "Product3"},
new() { Id = Guid.NewGuid(), Name = "Product5"}
});
await dbContext1.SaveChangesAsync();
}
currentTenant.SetTenant("Tenant2");
FieldIsolationServiceDbContext dbContext2 = await dbContext.CreateDbContextAsync();
if (await dbContext2.Set<Product>().IgnoreQueryFilters().CountAsync() < 6)
{
await dbContext2.AddRangeAsync(new List<Product>
{
new() { Id = Guid.NewGuid(), Name = "Product2"},
new() { Id = Guid.NewGuid(), Name = "Product4"},
new() { Id = Guid.NewGuid(), Name = "Product6"}
});
await dbContext2.SaveChangesAsync();
}
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Query;
using System.Linq.Expressions;
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
{
public static class EntityTypeBuilderQueryFilterExtensions
{
/// <summary>
/// Support multiple HasQueryFilter calls on same entity type
/// https://github.com/dotnet/efcore/issues/10275
/// </summary>
public static void AddQueryFilter<T>(this EntityTypeBuilder entityTypeBuilder, Expression<Func<T, bool>> expression)
{
ParameterExpression parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType);
Expression expressionFilter = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), parameterType, expression.Body);
LambdaExpression? currentQueryFilter = entityTypeBuilder.Metadata.GetQueryFilter();
if (currentQueryFilter is not null)
{
Expression currentExpressionFilter = ReplacingExpressionVisitor.Replace(currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body);
expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter);
}
LambdaExpression lambdaExpression = Expression.Lambda(expressionFilter, parameterType);
entityTypeBuilder.HasQueryFilter(lambdaExpression);
}
}
}
@@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using MultiTenancySample.FieldIsolationService.Entities;
using MultiTenancySample.ServiceDefaults;
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
{
public class FieldIsolationServiceDbContext(DbContextOptions<FieldIsolationServiceDbContext> options, ICurrentTenant currentTenant) : DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(32);
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.ClrType.IsAssignableTo(typeof(IMultiTenant)))
{
modelBuilder.Entity(entityType.ClrType).AddQueryFilter<IMultiTenant>(e => e.TenantId == currentTenant.TenantId);
}
}
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.AddInterceptors(new TenantSaveChangesInterceptor(currentTenant));
base.OnConfiguring(optionsBuilder);
}
}
}
@@ -0,0 +1,41 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using MultiTenancySample.FieldIsolationService.Entities;
using MultiTenancySample.ServiceDefaults;
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
{
public class TenantSaveChangesInterceptor(ICurrentTenant currentTenant) : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
if (eventData.Context is not null)
{
MultiTenancyTracking(eventData.Context);
}
return base.SavingChanges(eventData, result);
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (eventData.Context is not null)
{
MultiTenancyTracking(eventData.Context);
}
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
private void MultiTenancyTracking(DbContext dbContext)
{
IEnumerable<EntityEntry<IMultiTenant>> multiTenancyEntries = dbContext.ChangeTracker.Entries<IMultiTenant>().Where(entry => entry.State == EntityState.Added || entry.State == EntityState.Modified);
multiTenancyEntries?.ToList().ForEach(entityEntry =>
{
entityEntry.Entity.TenantId ??= currentTenant.TenantId;
});
}
}
}