将所有字符串值保存在小写中



我想在保存db之前降低所有字符串值。

有什么办法可以做到这一点,如何做?我还应该意识到任何绩效的影响吗?

实现它的一种方法是引入自定义类型以进行转换。类似:

[Serializable]
public class LowerCaseStringType : AbstractStringType, ILiteralType
{
    public LowerCaseStringType() : base(new StringSqlType())
    {
        //To avoid NHibernate to issue update on flush when the same string is assigned with different casing
        Comparer = StringComparer.OrdinalIgnoreCase;
    }
    public override string Name { get; } = "LowerCaseString";
    public override void Set(DbCommand cmd, object value, int index, ISessionImplementor session)
    {
        base.Set(cmd, ((string) value)?.ToLowerInvariant(), index, session);
    }
    //Called when NHibernate needs to inline non parameterized string right into SQL. Not sure if you need it
    string ILiteralType.ObjectToSQLString(object value, Dialect.Dialect dialect)
    {
        return "'" + ((string) value).ToLowerInvariant() + "'";
    }
    //If you also want to retrieve all values in lowercase than also override Get method
}

您可以将所需的属性映射到以下类型中:

<property name="Name" type="YourNamespace.LowerCaseStringType, YourAssemblyName">

,甚至将其注册为所有字符串映射的默认类型(至少对于最新的NHibernate 5.2是正确的):

//Somewhere before SessionFactory is created
TypeFactory.RegisterType(typeof(string), new LowerCaseStringType(), new[] {"string", "String"});

相关内容

  • 没有找到相关文章

最新更新