如何从NHibernate上的子选择中进行选择

时间:2011-09-21 14:59:49

标签: nhibernate criteria-api

如何使用NHibernate Criteria API映射此SQL?

SQL:

SELECT COUNT(*) FROM (
    SELECT FirstName, LastName FROM Employees GROUP BY FirstName, LastName
) AS Query

这是一个非常简单的查询,我的查询的SubSelect要复杂得多。

那么,任何想法?

3 个答案:

答案 0 :(得分:2)

我找到了问题的解决方案,这是一个非常大的黑客,但它按预期工作。

我必须获取生成的SQL并使用SELECT COUNT(*)查询将其包围。以下是执行此操作的代码:

public ISQLQuery BuildCountQuery(ICriteria criteria)
{
    CriteriaImpl c = (CriteriaImpl)criteria;
    SessionImpl s = (SessionImpl)c.Session;
    string entityOrClassName = ExtractRealClassName(c);

    SessionFactoryImpl factory = (SessionFactoryImpl)s.SessionFactory;
    String[] implementors = factory.GetImplementors(entityOrClassName);
    string implementor = implementors.Length == 0 ? null : implementors[0];
    var persister = (IOuterJoinLoadable)factory.GetEntityPersister(implementor);
    CriteriaLoader loader = new CriteriaLoader(persister, factory, c, implementor, s.EnabledFilters);
    SqlString sql = loader.SqlString.Insert(0, "SELECT COUNT(*) FROM (");
    sql = sql.Append(") AS Query");

    var parameters = loader.Translator.CollectedParameters;
    var sqlQuery = this.session.CreateSQLQuery(sql.ToString());
    for (int i = 0; i < parameters.Count; i++)
        sqlQuery.SetParameter(i, parameters.ElementAt(i).Value, parameters.ElementAt(i).Type);

    return sqlQuery;
}

private string ExtractRealClassName(CriteriaImpl criteria)
{
    Type rootEntityType = criteria.GetRootEntityTypeIfAvailable();
    if (rootEntityType.GetInterfaces().Contains(typeof(INHibernateProxy)))
        return criteria.GetRootEntityTypeIfAvailable().BaseType.FullName;
    else
        return criteria.EntityOrClassName;
}

答案 1 :(得分:1)

DetachedCriteria criteriaEmployees = DetachedCriteria.For<Employees>();
criteriaEmployees.SetProjection(Projections.CountDistinct("FirstName"));
ICriteria executableCriteria = criteriaEmployees.GetExecutableCriteria(Session);
int count = executableCriteria.UniqueResult<int>();

答案 2 :(得分:0)

DetachedCriteria可用于创建子查询。一些例子在documentation