Created
May 3, 2024 17:48
-
-
Save HamidMolareza/30bb9ec6fbf106c70c374c44c7d3bdeb to your computer and use it in GitHub Desktop.
Global Entity Framework filter for soft deleting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq.Expressions; | |
using ConsoleApp.Models; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.EntityFrameworkCore.Query; | |
namespace ConsoleApp.Data; | |
public class AppDbContext : DbContext { | |
protected override void OnModelCreating(ModelBuilder modelBuilder) { | |
base.OnModelCreating(modelBuilder); | |
SetDeleteFilter(modelBuilder); | |
} | |
private static void SetDeleteFilter(ModelBuilder modelBuilder) { | |
// https://stackoverflow.com/questions/65702049/using-global-query-filters-for-all-entities | |
Expression<Func<ISoftDelete, bool>> filterExpr = obj => !obj.Deleted; | |
foreach (var mutableEntityType in modelBuilder.Model.GetEntityTypes()) { | |
// check if current entity type is child of BaseModel | |
if (mutableEntityType.ClrType.IsAssignableTo(typeof(ISoftDelete))) { | |
// modify expression to handle correct child type | |
var parameter = Expression.Parameter(mutableEntityType.ClrType); | |
var body = ReplacingExpressionVisitor.Replace(filterExpr.Parameters.First(), parameter, | |
filterExpr.Body); | |
var lambdaExpression = Expression.Lambda(body, parameter); | |
// set filter | |
mutableEntityType.SetQueryFilter(lambdaExpression); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment