one of the fields is count(*) NHibernate

大兔子大兔子 提交于 2019-12-23 16:32:54

问题


Can I do mapping to query like this :

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

Currently , I'm using a native 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;}
}

mapping :

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

回答1:


Yes, you should use formula.

Your mappings might look like this:

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



回答2:


It depends on the business classes you want to use. You could have these classes;

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

class Account
{
  // ...
}

Then you map it "normally" as one-to-many. Don't forget to make use of lazy loading. You may make it bidirectional.

You may create an optimized query which prevents loading the accounts just to count them:

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

This produces quite a similar query then yours. You get a Person in the first column and the number of accounts in the second.



来源:https://stackoverflow.com/questions/4984910/one-of-the-fields-is-count-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!