https://github.com/birajmainali/global-query-filter-for-softdelete
This is a demonstration of soft delete as well as a global query filter for soft-deleted items
https://github.com/birajmainali/global-query-filter-for-softdelete
ef-core softdelete
Last synced: 11 months ago
JSON representation
This is a demonstration of soft delete as well as a global query filter for soft-deleted items
- Host: GitHub
- URL: https://github.com/birajmainali/global-query-filter-for-softdelete
- Owner: BirajMainali
- Created: 2021-06-18T15:44:39.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2021-09-19T13:37:59.000Z (over 4 years ago)
- Last Synced: 2025-01-04T18:13:07.781Z (over 1 year ago)
- Topics: ef-core, softdelete
- Language: C#
- Homepage:
- Size: 659 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# SoftDelete
This is a demonstration of soft delete as well as a global query filter for soft deleted items
``ApplicatonDbContext.cs``
```c#
public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = new CancellationToken())
{
foreach (var entry in ChangeTracker.Entries())
{
var entity = entry.Entity;
if (entry.State == EntityState.Deleted && entity is ISoftDelete)
{
entry.State = EntityState.Modified;
entity.GetType().GetProperty("RecStatus")?.SetValue(entity, 'D');
}
}
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
```
Note : If we Only Check the `EntityState.Deleted` So we need to add a filter every time to get Actual data like
```c#
_context.entity.where(x=>x.RecStatus == 'A')
```
But If we add the Global Filter like
``ApplicationDbContext.cs``
```c#
public void SetGlobalQuery(ModelBuilder builder) where T : GenericModel
{
builder.Entity().HasQueryFilter(e => e.RecStatus.Equals('A'));
}
static readonly MethodInfo SetGlobalQueryMethod = typeof(ApplicationDbContext)
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Single(t => t.IsGenericMethod && t.Name == "SetGlobalQuery");
private void AddSafeDeleteGlobalQuery(ModelBuilder builder)
{
foreach (var type in builder.Model.GetEntityTypes())
{
if (type.BaseType == null && typeof(ISoftDelete).IsAssignableFrom(type.ClrType))
{
var method = SetGlobalQueryMethod.MakeGenericMethod(type.ClrType);
method.Invoke(this, new object[] {builder});
}
}
}
```
It Execute every time `SetGlobalQuery`, so no need to add filter to get Actual Data