我正在尝试构建一个必须构建 Case 构造的自定义 Hql 生成器。此构造将在 order by 子句中使用。我正在尝试以当前用户的语言对枚举(在这种情况下为性别枚举)进行字母顺序排序。如您所见,排序顺序是从 GenderResourceTextAttribute 中检索的。订单数组中的值必须在 Case 构造中使用。这是我到目前为止所拥有的:
public override HqlTreeNode BuildHql(MethodInfo method, System.Linq.Expressions.Expression targetObject, ReadOnlyCollection<System.Linq.Expressions.Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
GenderResourceTextAttribute attribute = null;
if (targetObject.Type.IsEnum)
{
attribute = targetObject.Type.GetCustomAttributes(typeof(GenderResourceTextAttribute), false).FirstOrDefault() as GenderResourceTextAttribute;
}
int[] order = attribute.GetSortOrderPosition();
return treeBuilder.Case(new HqlWhen(....));
}
[GenderResourceText]
public enum Gender
{
Unknown = 0,
Men,
Women
}
我最终希望它生成类似于以下 sql 的内容:
case Gender when 0 then 1 when 1 then 2 else 0 end
我该如何实施?
编辑:根据 Gerben 的建议添加了我的解决方案:
谢谢格本!
通过您提供的示例,我能够完成它:
public override HqlTreeNode BuildHql(MethodInfo method, System.Linq.Expressions.Expression targetObject, ReadOnlyCollection<System.Linq.Expressions.Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
EnumResourceTextAttribute attribute = (EnumResourceTextAttribute)targetObject.Type.GetCustomAttributes(typeof(EnumResourceTextAttribute), false).FirstOrDefault();
IEnumerable<int> sortOrder = attribute.GetSortOrderPositions(arguments[0].ToString() == "Descending" ? System.Data.SqlClient.SortOrder.Descending : SortOrder.Ascending);
List<HqlExpression> parameters = new List<HqlExpression>();
List<HqlWhen> hqlWhenList = new List<HqlWhen>();
for(int index = 0; index < sortOrder.Count(); index++)
{
int position = sortOrder.ElementAt(index);
hqlWhenList.Add(
treeBuilder.When(
treeBuilder.Equality(visitor.Visit(targetObject).AsExpression(), treeBuilder.Constant(index)),
treeBuilder.Constant(position)
)
);
}
HqlCase hqlCase = treeBuilder.Case(hqlWhenList.ToArray());
return hqlCase;
}