以小写形式保存所有字符串值

问题描述 投票:1回答:1

我想在保存它们db之前将所有字符串值小写。

NHibernate有没有办法做到这一点以及如何做到这一点?还有我应该注意的性能影响吗?

nhibernate fluent-nhibernate fluent-nhibernate-mapping
1个回答
2
投票

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

[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"});
© www.soinside.com 2019 - 2024. All rights reserved.