Igor Monteiro
Igor Monteiro

Reputation: 953

Dynamic DTO from nhibernate projections criteria

I have a projection List in my c# code :

var criteria = DetachedCriteria.For(this.modelType);

         for (int i = 0; i < this.fields.Length; i++)
            projections.Add(Projections.Property(this.fields[i]));

        if (fields.Length > 0)
            criteria.SetProjection(projections);

if I don´t set any field in my projection my return is follow:

enter image description here

but if I set projections in my code, my result is follow:

enter image description here

How can I convert the list with projections in a Dynamic DTO object?

Upvotes: 1

Views: 1497

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

What we need is transformer:

criteria
    .SetResultTransformer(
      NHibernate.Transform.Transformers.AliasToBean<MyEntity>())

or without generic

criteria
    .SetResultTransformer(
      NHibernate.Transform.Transformers.AliasToBean(this.modelType))

The point with transformers is to use aliasing (see the .As()):

.SetProjection(Projections.ProjectionList()
  .Add(Projections.Property("Property1").As("Property1"))
  .Add(Projections.Property("Property2").As("Property2"))
  .Add(Projections.Property("Property3").As("Property3"))
)

Check more here e.g.:

Upvotes: 1

Related Questions