1

I want to query an nhibernate mapped class but the result should be an unmapped object. The mapped and unmapped classes look like this:

[Class(NameType = typeof(ClassA)]
public class ClassA
{
    [Cache(0, Usage = CacheUsage.ReadWrite)]
    [Id(1, Name = "Id", UnsavedValue = null)]
    [Generator(2, Class = "native")]
    public virtual long? Id { get; set; }

    [Property]
    public virtual string PropertyA { get; set; }

    [Property]
    public virtual string PropertyB { get; set; }

}

public class ClassB
{
    public string PropertyA { get; set; }

    public string PropertyB { get; set; }

    public int Number { get; set; }
}

And I use this method to get the result I want:

public ICollection<ClassB> Group()
{
    var result =
        Session.CreateCriteria(typeof(ClassA)).SetProjection(
            Projections.ProjectionList().Add(Projections.RowCount(), "Number")
                   .Add(Projections.GroupProperty("PropertyA"))
                   .Add(Projections.GroupProperty("PropertyB")));

    return
        (result.List().Cast<IList>().Select(
            entry =>
            new ClassB {
                        Number = (int)entry[0],
                        PropertyA = (string)entry[1],
                        PropertyB = (string)entry[2] 
                    }
             )).ToList();
}

This works fine, but isn't there a more direct way to do this using the criteria-api?

Rian Schmits
  • 3,096
  • 3
  • 28
  • 44

1 Answers1

7

Yes just do

result.SetResultTransformer(Transformers.AliasToBean<ClassB>());
result.List<ClassB>();

You will also need to wrap your property projections as Aliases Projections.Alias(Projections.GroupProperty("PropertyA"), "PropertyA")

Vadim
  • 17,897
  • 4
  • 38
  • 62
  • Thanks, that works perfectly. I only had give the projections an explixit alias to get it working, like this: `.Add(Projections.GroupProperty("PropertyA"), "PropertyA")` – Rian Schmits Feb 26 '11 at 17:57