Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...