How to automate trimming strings in Entity Framework

When working with legacy data where the data being loaded into SQL server tables contains trailing spaces, the trailing spaces will remain in the fields regardless of whether the fields are varchar  This poses problems when doing compares or extracting data to files as you may not get the results you are looking for.

One solution would be to add a trim to each field where this occurs.  This will result in having trims scattered all over your code base.

Another and better solution would be to add an interception for Entity Framework that will trim all fields of certain data types.

String Interceptor class

StringTrimmerInterceptor

As you can see, this will trim fields of types nvarchar, varchar, char, and nchar.  In the SQL generated, it will add a LTRIM and RTRIM to each field.

To implement this interceptor, you just need to register it in a separate class within the same assembly.

EfConfiguration

I found this solution based on Rowan Miller’s EF6.1–Workaround Trailing Blanks Issue In String Joins

Comments

  1. Connie DeCinko says

    Getting an error: Using the generic type ‘StringTrimmerInterceptor’ requires 1 type arguments

  2. Willians Rodriguez says

    Hi, what changes i have to do with do something like that with the numeric fields to avoid null and return always 0 instead

    thanks in advance

Leave a Reply to Willians Rodriguez Cancel reply

*