如何使用Entity Framework修剪字符串?

Nad*_*udi 6 c# entity-framework

如何让Entity Framework在将所有字符串存储到数据库之前自动修剪它们?

Ric*_*der 9

您可以IDbCommandInterceptor用来拦截对数据库的所有调用.然后修剪任何传递的参数.

有关更多详细信息,请参阅此文章,尤其是如何注册拦截器.

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
}
Run Code Online (Sandbox Code Playgroud)