Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim string with Entity Framework?

How to make Entity Framework automatically trim all strings before storing them in database?

like image 952
Nadir Mezhoudi Avatar asked Sep 22 '15 23:09

Nadir Mezhoudi


1 Answers

You can use IDbCommandInterceptor to intercept all calls to the database. Then trim any parameters being passed.

See this article for more details and especially how to register the interceptor.

class TrimCommandInterceptor: IDbCommandInterceptor
{
  public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> ctx)
  {
    foreach (var p in command.Parameters)
    {
       if (p.Value is string)
         p.Value = ((string) p.Value).Trim();
    }
  }

  // Add all the other interceptor methods
}
like image 99
Richard Schneider Avatar answered Oct 20 '22 09:10

Richard Schneider