Search code examples
c#nhibernatecriteriadtonhibernate-criteria

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?


Solution

  • 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.: