How to make Entity Framework automatically trim all strings before storing them in database?
Asked
Active
Viewed 2,972 times
1 Answers
10
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
}

Richard Schneider
- 34,944
- 9
- 57
- 73
-
You must cast `p` to `DbParameter` to get access to the Value Property: `foreach (DbParameter p in command.Parameters)` – fsbflavio Apr 14 '20 at 21:05