NHibernate - execute SQL to populate DTO

I have several instances for reports where running sprocs is simpler and easier than complex QueryOver statements.

I have a DTO, not an entity that represents the data returned from the query and wants to populate the query results in the DTO. I use named queries and session.GetNamedQuery () to execute the query.

  • Should I create mapping files for DTO?
  • If so, is it possible for NHibernate / FluentNHibernate to know that it should not create tables for DTO? My unit tests fail and create a schema using NH SchemaExport tool and don't want to create tables for DTO

Note: I don't want to project a QueryOver / Linq query using Projections and AliasToBean - I need to execute a stored procedure.

Greetings

+5
source share
2 answers

With CreateSQLQuery, the following will work without any mapping file. Perhaps you can try with named queries:

public class YourDto
{
    public int YourDtoId { get; set; }
    public string YourDtoTitle { get; set; }
}

then

var result = yourNhSession
    .CreateSQLQuery("select yourColumn1 as YourDtoId, yourColumn2 as YourDtoTitle from YOUR_TABLE")
    .SetResultTransformer(Transformers.AliasToBean<YourDto>())
    .List<YourDto>();
+9
source

If you need the simplest solution, I suggest you add micro / orm to your architecture, such as Dapper . It just drops one file in your project and follows the pattern. For me, this is the best solution for couples to NH, when you need to do things that for some reason are not related to the logic of the entity.

+2
source

All Articles