2011-02-13 57 views
3

我可以做映射到这样的查询:的领域之一是COUNT(*)NHibernate的

select id,name,address,(select count(*) from account where record_id=id) as counter 
from data where id = :id 

目前,我使用的是本地SQL。

class person 
{ 
    public virtual long Id{get;set;} 
    public virtual string Name{get;set;} 
    public virtual string Address{get;set;} 
    public virtual long Counter{get;set;} 
} 

映射:

<property name="Counter" formula="(select count(*) from account where record_id=id)"  type="long"/> 
+0

好吧,现在我明白你想要使用的类。我调整了我的答案,请看看。 – 2011-02-14 07:46:44

回答

5

是的,你应该使用formula

你的映射可能是这样的:

<property name="CountOfAccounts" 
    formula="(select count(*) from account where account.id = id)"/> 
+0

谢谢。但现在我有一个“对象引用未设置为对象的实例” – Lampa 2011-02-13 16:18:15

3

这取决于你想使用的业务类。你可以有这些课程;

class Person 
{ 
    int Id { get; private set; } 
    string Name { get; set; } 
    string Address { get; set; } 
    IList<Account> Accounts { get; private set; } 
} 

class Account 
{ 
    // ... 
} 

然后,您将它映射为“正常”为一对多。不要忘记利用延迟加载。你可以使它成为双向的。

您可以创建这样可防止加载帐户的优化的查询只算来:

select 
    p, 
    size(p.Accounts) 
from 
    Person p 
where 
    p.id = :id 

这将产生非常类似的查询,然后你的。您在第一列中获得一个人,在第二列中获得账户数量。