简体   繁体   English

如何将NHibernate查询修改为类似于简单SQL的行为?

[英]How to modify an NHibernate query to behave like simple SQL?

I'm trying to modify the following code so that it will return a Dictionary<int,int> where the keys correspond to groupId and the values correspond to the total companies in the group, instead of a List<Company> 我正在尝试修改以下代码,以便它将返回Dictionary<int,int> ,其中键对应于groupId,值对应于组中的公司总数,而不是List<Company>

companies = _session.CreateCriteria<Company>()
    .Add<Company>(x => x.CompanyGroupInfo.Id == groupId)
    .List<Company>();

Unfortunately, I'm not really familiar with NHibernate at all.. 不幸的是,我对NHibernate一点都不熟悉。

This is the SQL I'm supposed to base the new code on, because this SQL produces the correct result: 这是我应该基于新代码的SQL,因为此SQL产生正确的结果:

SELECT
      [CompanyInfo_GroupId]
      ,count([Company_Id]) TotalNumberOfCompanies
FROM 
      [Company]
      inner join [CompanyInfo]
            on [CompanyInfo].[CompanyInfo_MSCompanyId] 
                = [Company].[Company_Id]
where
      -- I have an array of GroupIds that I get the ids from 
      [CompanyInfo_GroupId] in(963, 1034) 
group by
      [CompanyInfo_GroupId]

which outputs a table as follows: 输出的表如下:

CompanyInfo_GroupId TotalNumberOfCompanies
------------------- ----------------------
963                 5
1034                1

Can somebody please give me a few pointers? 有人可以给我一些建议吗? Thanks 谢谢

我认为您应该看看投影,汇总和分组

Here's how that query might look in Criteria... 以下是该查询在“条件”中的显示方式...

session.CreateCriteria<Company>()
    .CreateAlias("CompanyInfo", "cnfo", InnerJoin)
    .Add(Restrictions.In("cnfo.Group.id", new int[] {963, 1034}))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty("cnfo.Group.id"), "CompanyInfoGroupID")
        .Add(Projections.RowCount(), "TotalNumberOfCompanies"))
    .SetResultTransformer(Transformers.AliasToBean<SomeDTO>())
    .List<SomeDTO>();

...

public class SomeDTO
{
    public int CompanyInfoGroupID { get; set; }
    public int TotalNumberOfCompanies { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM