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

查看:27
本文介绍了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;}     
}

然后,您创建一个 Criteria 查询,在该 Criteria 中您定义要检索所有人员.但是,您可以指定 NHibernate 不应返回 Person 对象,而是 PersonView 对象.为了能够做到这一点,您需要使用投影和 AliasToBeanTransformer:

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 将为您的 Criteria 生成一个查询,它看起来很像:

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天全站免登陆