Nadir Mezhoudi
Nadir Mezhoudi

Reputation: 155

How to trim string with Entity Framework?

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

Upvotes: 8

Views: 3237

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35477

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
}

Upvotes: 10

Related Questions