Skip to content

Instantly share code, notes, and snippets.

@0xced
Created November 13, 2018 15:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xced/b85cbf747c8289e7758b4af216996d0d to your computer and use it in GitHub Desktop.
Save 0xced/b85cbf747c8289e7758b4af216996d0d to your computer and use it in GitHub Desktop.
Entity Framework interceptor to trim strings (remove leading and trailing spaces) before saving to database
using System.Data.Entity;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
namespace gist
{
/// Adapted from https://stackoverflow.com/questions/20133696/how-can-i-configure-entity-framework-to-automatically-trim-values-retrieved-for/27504530#27504530
/// and https://stackoverflow.com/questions/42845669/idbcommandtreeinterceptor-for-exact-dbcontext/42861024#42861024
internal class StringTrimmerInterceptor<T> : IDbCommandTreeInterceptor where T : DbContext
{
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace && interceptionContext.DbContexts.All(e => e.GetType() == typeof(T)))
{
if (interceptionContext.Result is DbQueryCommandTree queryCommand)
{
var newQuery = queryCommand.Query.Accept(new StringTrimmerQueryVisitor());
interceptionContext.Result = new DbQueryCommandTree(queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
}
}
}
}
internal class StringTrimmerQueryVisitor : DefaultExpressionVisitor
{
private static readonly string[] TypesToTrim = { "nvarchar2", "nvarchar", "varchar", "char", "nchar" };
public override DbExpression Visit(DbNewInstanceExpression expression)
{
var arguments = expression.Arguments.Select(a =>
{
if (a is DbPropertyExpression propertyArg && TypesToTrim.Contains(propertyArg.Property.TypeUsage.EdmType.Name))
{
return a.Trim();
}
return a;
});
return expression.ResultType.New(arguments);
}
}
}
@xts-velkumars
Copy link

@0xced how do Implement same logic in .NET 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment