Search code examples
c#nhibernatenhibernate-criteria

NHibernate query returning unmapped object using Criteria-api


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?


Solution

  • 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")