Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - NHibernate and Collection Counts

I have the following class setup for persistence using NHibernate

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

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;}     
}

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));

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>

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...