NHibernate count another entity with sub query?

房东的猫 提交于 2019-12-10 19:27:18

问题


I have two entities which are:

User
{
    UserGuid,
    Address,
    .
    .
    .
    EmailCount // This is not a column in the database, 
               // I just wanna get the count number from the UserEmail table
               // and map the value to this property
}

UserEmail
{
    UserGuid,
    Timestamp
}

The issue is how can I get the email count with a sub query in NHibernate?

By far I have this, but it does not work. Any idea?

User userEntity = null;

var subQuery = QueryOver.Of<UserEmail>()
    .Where(ue => ue.UserGuid == userEntity.UserGuid)
    .ToRowCountQuery();                       

return _session.StatefulSession.QueryOver(() => userEntity)
          .WithSubquery.WhereValue("EmailCount").Eq(subQuery)
          .List();

回答1:


This would be the way how to use subquery to get an inlined count with a QueryOver syntax:

User userEntity = null;

var subQuery = QueryOver
    .Of<UserEmail>()
    .Where(ue => ue.UserGuid == userEntity.UserGuid)
    .ToRowCountQuery(); 

var list = _session.StatefulSession
    .QueryOver<User>(() => userEntity)
    .SelectList(projections => projections
        .Select(x => x.UserGuid)
             .WithAlias(() => userEntity.UserGuid)
        .Select(x => x.Address)
             .WithAlias(() => userEntity.Address)
        // any property to be selected
        ... 
        // INLINE COUNT
        // our subquery placed into play
        .SelectSubQuery(subQuery)
             // this will populate virtual/not mapped EmailCount
             .WithAlias(() => userEntity.EmailCount) 
    )
    .TransformUsing(Transformers.AliasToBean<User>())
    //.Take(10).Skip(100) // paging
    .List();


来源:https://stackoverflow.com/questions/24513919/nhibernate-count-another-entity-with-sub-query

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