Reputation: 155
How to make Entity Framework automatically trim all strings before storing them in database?
Upvotes: 8
Views: 3237
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