using IM.DomainCommons; using Microsoft.EntityFrameworkCore; using System.Linq.Expressions; namespace IM.Infrastructure.Efcore { public static class EfcoreExtension { public static void EnableSoftDeletionGlobalFilter(this ModelBuilder modelBuilder) { var entityTypesHasSoftDeletion = modelBuilder.Model.GetEntityTypes() .Where(e => e.ClrType.IsAssignableTo(typeof(ISoftDelete))); foreach (var entityType in entityTypesHasSoftDeletion) { var isDeletedProperty = entityType.FindProperty(nameof(ISoftDelete.IsDeleted)); var parameter = Expression.Parameter(entityType.ClrType, "p"); var filter = Expression.Lambda(Expression.Not(Expression.Property(parameter, isDeletedProperty.PropertyInfo)), parameter); entityType.SetQueryFilter(filter); } } public static IQueryable Query(this DbContext context) where T : class { return context.Set().AsNoTracking(); } } }