在保存字符串之前,我想小写所有字符串值。
NHibernate有什么方法可以做到这一点,怎么做?还有我应该意识到的任何性能影响吗?
答案 0 :(得分: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"});