Created
May 2, 2024 07:10
-
-
Save 0xced/28480a475fc660e9ee4f16bee0077153 to your computer and use it in GitHub Desktop.
Entity Framework Core interceptor to trim strings (remove leading and trailing spaces) before saving to database
This file contains 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; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.EntityFrameworkCore.Diagnostics; | |
namespace gist; | |
public class StringTrimmerInterceptor : ISaveChangesInterceptor | |
{ | |
public InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result) | |
{ | |
if (eventData.Context != null) | |
{ | |
TrimStrings(eventData.Context); | |
} | |
return result; | |
} | |
public ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default) | |
{ | |
if (eventData.Context != null) | |
{ | |
TrimStrings(eventData.Context); | |
} | |
return ValueTask.FromResult(result); | |
} | |
private static void TrimStrings(DbContext dbContext) | |
{ | |
var stringProperties = dbContext.ChangeTracker.Entries() | |
.Where(e => e.State is EntityState.Added or EntityState.Modified) | |
.SelectMany(e => e.Properties) | |
.Where(p => p.CurrentValue != null && p.Metadata.ClrType == typeof(string)); | |
foreach (var property in stringProperties) | |
{ | |
var currentValue = (string)property.CurrentValue!; | |
property.CurrentValue = currentValue.Trim(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment