NHibernate和集合计数 [英] NHibernate and Collection Counts

查看:92
本文介绍了NHibernate和集合计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NHibernate

I have the following class setup for persistence using NHibernate

public class Person
{
    public string Name { get; set; }
    public IList<Person> Subordinates { get; set; }
}

现在说我有两列,名称和网格下属什么是NHibernate的同时保留了使用域对象尽可能的这样做的最佳方式的数量。

Now say I have a grid with two columns, "Name" and "Number of Subordinates" what is the best way of doing this in NHibernate whilst retaining the use of domain objects where possible.

感谢

推荐答案

您可以创建您使用例如报表/概述一个DTO类...
这个类可能是这样的:

You could create a DTO class that you use for reporting / overviews for instance... This class could look like this:

public class PersonView
{
     public string Name{ get;set; }
     public int NumberOfSubordinates{get;set;}     
}



然后,您创建一个标准的查询,在该标准定义了要检索的所有人员。
但是,您可以指定NHibernate的不应该返回Person对象,但是PersonView对象。为了能够做到这一点,你需要使用的投影和Alias​​ToBeanTransformer:

Then, you create a Criteria query, in in that Criteria you define that you want to retrieve all Persons. However, you can specify that NHibernate should not return Person objects, but PersonView objects. In order to be able to do this, you'll need to use a projection and an AliasToBeanTransformer:

ICriteria crit = new Criteria(typeof(Person));

crit.SetProjection (Projections.ProjectionList()
                       .Add (Projections.Property("Name"), "Name")
                       .Add (Projections.Count ("Subordinates"), "NumberOfSubordinates");

crit.SetResultTransformer(Transformers.AliasToBean (typeof(PersonView));

喜欢的东西上面。(我没有测试您的具体情况)。
然后,你就必须让NHibernate的知道PersonView类的存在,通过简单的'进口这个类。
我有一个hbm.xml文件中,在这里我输入我的DTO类。这看起来像

Something like the above. (I didn't test your specific situation). Then, you just have to let NHibernate know of the existence of the PersonView class, by simply 'importing' this class. I have one hbm.xml file, where I import all my DTO classes. This looks like

<hibernate-mapping .. >
  <import class="PersonView" />
</hibernate-mapping>

然后,NHibernate的会为您条件的查询非常类似于:

Then, NHibernate will generate a query for your Criteria that pretty much looks like:

SELECT p.Name, COUNT(p.Subordinates) FROM Person
INNER JOIN Subordinates ON Person.PersonId = Subordinates.PersonID
GROUP BY p.Name

这篇关于NHibernate和集合计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆