以小写形式保存所有字符串值
Save all string values in lowercase
我想在将所有字符串值保存为 db 之前将它们小写。
NHibernate 有什么方法可以做到这一点吗?如何做到的?还有什么我应该注意的性能影响吗?
实现它的一种方法是引入自定义类型进行转换。类似于:
[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"});
我想在将所有字符串值保存为 db 之前将它们小写。
NHibernate 有什么方法可以做到这一点吗?如何做到的?还有什么我应该注意的性能影响吗?
实现它的一种方法是引入自定义类型进行转换。类似于:
[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"});