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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works perfectly. I only had give the projections an explixit alias to get it working, like this: .Add(Projections.GroupProperty("PropertyA"), "PropertyA")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.