所以我有以下sql
SELECT * FROM 表,其中名称 COLLATE LATIN1_GENERAL_CI_AI LIKE 'myText%'
我想使用 QueryOver 来实现
目前我有:
whereRestriction.Add(Expression.Sql("Name COLLATE LATIN1_GENERAL_CI_AI LIKE ?", String.Format("{0}%", subStringMatch), HibernateUtil.String));
工作正常,但有两个问题。首先它是 sqlserver 特定的,其次数据库列“名称”是硬编码的。
有没有人有任何建议来解决这两个问题,或者至少是硬编码的数据库列名称?
最佳答案
我就是这样实现的。不知道有没有更好的办法...
我。 Like 表达式,受益于现有的 Like 表达式
public class LikeCollationExpression : LikeExpression
{
const string CollationDefinition = " COLLATE {0} ";
const string Latin_CI_AI = "LATIN1_GENERAL_CI_AI";
// just a set of constructors
public LikeCollationExpression(string propertyName, string value, char? escapeChar, bool ignoreCase) : base(propertyName, value, escapeChar, ignoreCase) { }
public LikeCollationExpression(IProjection projection, string value, MatchMode matchMode) : base(projection, value, matchMode) { }
public LikeCollationExpression(string propertyName, string value) : base(propertyName, value) { }
public LikeCollationExpression(string propertyName, string value, MatchMode matchMode) : base(propertyName, value, matchMode) { }
public LikeCollationExpression(string propertyName, string value, MatchMode matchMode, char? escapeChar, bool ignoreCase) : base(propertyName, value, matchMode, escapeChar, ignoreCase) { }
// here we call the base and append the COLLATE
public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters)
{
// base LIKE
var result = base.ToSqlString(criteria, criteriaQuery, enabledFilters);
var sqlStringBuilder = new SqlStringBuilder(result);
// extend it with collate
sqlStringBuilder.Add(string.Format(CollationDefinition, Latin_CI_AI ));
return sqlStringBuilder.ToSqlString();
}
}
二.自定义扩展方法
public static class QueryOverExt
{
// here: WhereLikeCiAi()
public static IQueryOver<TRoot, TSubType> WhereLikeCiAi<TRoot, TSubType>(
this IQueryOver<TRoot, TSubType> query
, Expression<Func<TSubType, object>> expression
, string value
, MatchMode matchMode)
{
var name = ExpressionProcessor.FindMemberExpression(expression.Body);
query
.UnderlyingCriteria
.Add
(
new LikeCollationExpression(name, value, matchMode)
);
return query;
}
}
三. QueryOverAPI 中的用法
...
query.WhereLikeCiAi(c => c.Name, "searchedString", MatchMode.Anywhere);
关于没有硬编码列名的 Nhibernate QueryOver 排序规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704229/