Vladimir Nani
Vladimir Nani

Reputation: 2874

NHibernate DTO mapping

  1. Is it OK to create Mappings for DTO objects and then query them instead of domain? If it is not explain why?
  2. What If i need couple of those dtos?

Upvotes: 5

Views: 8770

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38598

You don't need to map/persist a DTO object. It's normaly to readonly data and send to other layer of your application (web services, views, etc...).

You can create a query on the Person entity that returns a PersonDTO list. Take a look at SetResultTransformer method. Try somethin like this:

var query = session.CreateQuery("select p.FirstName, p.Age from Person p order by p.FirstName")
                   .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(PersonDTO)))
                   .List<PersonDTO>();

And your DTO:

public class PersonDTO 
{
   public string FirstName { get; set; }
   public int Age { get; set; }
}

The result of the column on the hql query should have the same name of your DTO's properties to NHibernate do the right reflection when construct the DTO and hydrate the object.

Linq

You also can use linq to have a DTO (or a list of DTOs) as a result. For sample:

var query = Session.Query<Person>().OrderBy(x => x.FirstName)
                   .Select(x = new PersonDTO() { FirstName = x.FirstName, Age = x.Age })
                   .ToList();

Look this article: http://gustavoringel.blogspot.com.br/2009/02/creating-dto-in-nhibernate-hql-using.html

Upvotes: 10

Related Questions