How To

Tips Of The Week: EF CORE – Trim String Entries Before Saving

Reading Time: 1 minute

EF Core doesn’t have a built in way to trim string entries (your data models / records) automatically but with just a few lines of code you can accomplish this yourself.

 

Step 1.

Simply create a function that accepts the DbContext.

In the function you will get all the entries the context is tracking. If you wish you could filter out only Added and Modified entries. Loop through the entries and get the properties (representing your columns) that are of type string. Then simply perform a trim on the ones that are not null.

 

public void OnBeforeSaving(DbContext context)
{
    var entries = context?.ChangeTracker?.Entries();

    if (entries == null)
    {
        return;
    }

    foreach (var entry in entries)
    {
        // get all the properties and are of type string
        var propertyValues = entry.CurrentValues.Properties.Where(p=> p.ClrType == typeof(string));

        foreach (var prop in propertyValues)
        {
            // access the correct column by it's name and trim the value if it's not null
            if (entry.CurrentValues[prop.Name] != null) entry.CurrentValues[prop.Name] = entry.CurrentValues[prop.Name].ToString().Trim();
        }
    }
}

Step 2.

To Execute the logic just override the `SaveChanges` and `SaveChangesAsync`, execute your custom rules first and then call the base implementation

 

public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
    // do our custom rules
    OnBeforeSaving();
    return base.SaveChanges(acceptAllChangesOnSuccess);
            
}

public override async Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
{
    // do our custom rules
    OnBeforeSaving();
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
            
}