NHibernate DOM mapping

  • Can I create mappings for DTO objects and then query them instead of a domain? If this does not explain why?
  • What if I need a couple of these dtos?

  • DTos are read-only
  • ID auto generated NH
  • In the future, these dtos will have established mappings for related dtos.
  • I use DTO to reduce request size

    <class name="Person" table="`APP_Person`"> <property name="FirstName" type="string" length="512" /> <property name="Age" type="int" /> <property name="SocialNumber" type="int" /> <property name="PassportId" type="int" /> <property name="Salary" type="int" /> </class> <class name="PersonDTO" table="`APP_Person`"> <property name="FirstName" type="string" length="512" /> <property name="Age" type="int" /> </class> 
+4
source share
1 answer

You do not need to display / save the DTO object. This is normal for reading only data and sending it to another level of your application (web services, views, etc.).

You can create a query for a Person object that returns a PersonDTO list. Take a look at the SetResultTransformer method. Try something 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 hql query hql must have the same name for your DTO properties so that NHibernate will correctly reflect when building the DTO and hydrate the object.

Linq

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

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

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

+9
source

All Articles