How to make Entity Framework automatically trim all strings before storing them in database?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With