我想爲nHibernate和QueryOver創建List()的泛型方法。我已經達到了想要添加連接的程度,但是如果沒有指定我要加入的泛型類型,我不認爲我可以這樣做......這不會使它變得如此動態,因爲每個泛型都必須聲明。有沒有任何地方可以有一個動態的連接列表?代碼如下:nHibernate動態加入QueryOver
public static IList<T> QueryOver<T>(
Dictionary<Expression<Func<T, object>>, JoinType> joins,
List<Expression<Func<T, bool>>> predicates,
Dictionary<Expression<Func<T, object>>, System.Web.UI.WebControls.SortDirection> sortList,
int? maxResults
) where T : class
{
IList<T> results;
IQueryOver<T, T> query;
results = null;
// open the session
using (ISession session = OpenSession())
{
// begin a transaction
using (ITransaction transaction = session.BeginTransaction())
{
try
{
// declare the query
query = session.QueryOver<T>();
// joins
if (joins != null && joins.Count > 0)
{
foreach (KeyValuePair<Expression<Func<T, object>>, JoinType> join in joins)
{
// required to specify the type in the format query.JoinQueryOver<SubType>(join.Key, join.Value)
// BUT this means that it's not so dynamic because each SubType would have to be specified in the method call, yes?
query = query.JoinQueryOver(join.Key, join.Value);
}
}
// apply the where clauses
if (predicates != null && predicates.Count > 0)
{
foreach (Expression<Func<T, bool>> predicate in predicates)
{
query = query.Where(predicate);
}
}
// apply the sorting
if (sortList != null && sortList.Count > 0)
{
foreach (KeyValuePair<Expression<Func<T, object>>, System.Web.UI.WebControls.SortDirection> sort in sortList)
{
if (sort.Value == System.Web.UI.WebControls.SortDirection.Ascending)
{
query = query.OrderBy(sort.Key).Asc;
}
else
{
query = query.OrderBy(sort.Key).Desc;
}
}
}
// max results
if (maxResults.HasValue && maxResults.Value > 0)
{
query = (IQueryOver<T, T>)query.Take(maxResults.Value);
}
results = query.List();
// no errors, commit the transaction
transaction.Commit();
}
catch (Exception ex)
{
// error, rollback
transaction.Rollback();
// throw the exception and let the business logic deal with it
throw ex;
}
}
}
return results;
}