Search code examples
c#nhibernatedtoresulttransformer

NHibernate and DTOs to return specific data from hierarchical data


I have several tables that I need to pull data from but I do not need all of the data in all of the tables. So for example I have the following Order object that contains several child objects and object collections.

 public class Order
{
    public virtual int ID { get; set; }
    public virtual Coupon CouponID { get; set; }  
    public virtual Status StatusID { get; set; }
    public virtual Address ShippingAddressID { get; set; }
    public virtual Address BillingAddressID { get; set; }    
    public virtual ICollection<OrderShipmentHistory> OrdertHistories { get; set; }
    public virtual ICollection<OrderShipmentNote> OrderNotes { get; set; }      
    public virtual ShippingDetails ShippingDetail { get; set; }
    public virtual ICollection<OrderProduct> OrderProducts { get; set; }
}

Also some of these child objects in turn have child objects and at the most extreme we have a 4 tier object hierarchy.

So my problem is that I need to retrieve a list of objects that contain only specific information from most of these child objects.

Currently when I retrieve the list of orders I am pulling everything back. I have used lazy loading so that I don't do this but I will eventually need to pull this information back as I am accessing at least one piece of data in each of these child objects.

So I was thinking that instead of populating a list of orders I could create DTO's for each of the data collections that I need. My problem is I am not sure where to start. I have seen examples of people using DTO's but are only populating them once they have retrieved all of the data. I don't want to do this. I want to only retrieve the data I need and then populate the DTO's with the result sets.

I would really appreciate any guidance on where I should start and what I should be using.

regards

Noel.


Solution

  • What you are talking about is called projection.

    To project your object graph to a flattened structure use for example linq select.

    Now within the select you can either directly create the data strongly typed with your Dto or just return an IEnumerable<T> where T is dynamic or some other Poco and pass this around...

    Simple example of projection: Lets say foo is a Queryable coming from nhibernate...

    // Creates anonymous type with one property 'bar'
    var list = foo.Select(p => new { p.bar }).ToList();
    
    // Creates a Dto for each element and set property Bar of the Dto.
    var list = foo.Select(p => new Dto{ Bar = p.bar }).ToList();