Created
November 13, 2018 15:49
-
-
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
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.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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@0xced how do Implement same logic in .NET 6