Using NHibernate Transformer to get DTO

I’m slowly adopting Grey Young’s recent topic of CQS – Command Query Separation, sometimes we don’t need a rich domain object for very simple purpose. Most people call it as DTO. Those ‘DTO’ don’t need mapping file. Because they are not translated from domain object, instead they can be ‘transformed’ from NHibernate SQLQuery.

Ayende has an example of SQLQuery using AliasToBeanResultTransformer, here is another example of  PositionalToBeanResultTransformer from Gustavo, which needs add query into mapping file.

I like to keep query out of mapping file, adopt AliasToBeanResultTransformer:


public OrganizationAuditD FindByOrgIdAndAction(long id, string changCode)
 {
 IQuery query = Session.CreateSQLQuery(
 @"select a_Su_Id from dbo.z_Organization_AV  where a_Stakeholder_Id = :id and a_change_code = :changCode")
 .AddScalar("a_Su_Id", NHibernateUtil.String)
 .SetInt64("id", id)
 .SetString("changCode", changCode)
 .SetResultTransformer(new AliasToBeanResultTransformer(typeof(OrganizationAuditD) ))
 ;

 return query.List<OrganizationAuditD>()[0];
 }

My OrganizationAuditD DTO only has one meaningful property: a_Su_Id, that all I need. No other domain property / behavior at all.

Advertisements

2 thoughts on “Using NHibernate Transformer to get DTO

  1. The reservation I have with creating DTOs directly from the DB is that you have to change multiple DTOs whenever the DB structure changes. If you build them from domain objects then at least your app fails to compile if you rename or remove a member.

    CQS is supposed to help to enforce the “tell don’t ask” approach because you cannot access properties of your domain classes. I don’t think it does though. All you are doing is moving the “ask” out of strongly typed classes and into weakly formed SQL JOIN queries.

  2. Using alias name in query at the very beginning can reduce column renaming headache.

    An other extreme example of CQS might be re-using the existing search stored procedure.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s