If I were doing this using PHP and MySQL, it would look something like this (disclaimer that this PHP code is not suitable for external/web-facing use, as it's vulnerable to SQL injection):
<?php
function orderByColumns ($columns, $sql) {
if (0 < count($columns)) {
$column = array_shift($columns);
if (! stripos($sql, "ORDER BY")) {
$sql .= " ORDER BY";
}
$sql .= " {$column['name']} {$column['dir']}";
$sql .= 0 < count($columns) ? "," : "";
return orderByColumns($columns, $sql);
}
return $sql;
}
$columns = array(
array(
"name" => "foo",
"dir" => "ASC"
),
array(
"name" => "bar",
"dir" => "DESC"
)
);
$sql = "SELECT * FROM baz";
$sql = orderByColumns($columns, $sql); // And from here I could make my query
The point is that $columns
is to be an input from a user somewhere, and that that could be used to order the columns without knowing the list in advance, and in a method that is reusable.
I'm looking for a way to do something similar using C# and specifically NHibernate, but it doesn't really seem to work. Here is something along the lines of what I've been trying in C#:
List<string> columns = new List<string>()
{
"Column1",
"Column2",
"Column3"
// And there could be more.
}
string column = columns.First();
fq = foo.Queryable.OrderBy(
i => i.GetType().GetProperty(column).GetValue(i, null)
);
foreach (string column in columns)
{
fq = fq.ThenBy(
i => i.GetType().GetProperty(column).GetValue(i, null)
);
}
And, I've looked at a few StackOverflow answers (ok, more than a few), but they don't seem to be addressing how to build NHibernate queries dynamically in the way I'm looking for. The one that felt most promising is Dynamic QueryOver in nHibernate, but I'm having a hard time fully grokking whether that's even in the right direction.