nHibernate criteria ResultTransformer not working

570 Views Asked by At

I have (long and complcated) query, based on Criteria.

The following code:

//....
var myList = criteria.List<MyEntity>()

works fine, but it returns list of 50 whole entities. For performance reasons, i want to apply projection for my query. The following code also works OK:

  criteria.SetProjection(
    Projections.ProjectionList()
       .Add(Projections.Property("Id"))
       .Add(Projections.Property("Numer")));

   var objList =  criteria.List<Object[]>()

It returns collection of 50 arrays, each contains 2 objects, which I can access by indexes. I want to access individual properties by it's names, so I wrote the following code:

        criteria.SetProjection(
            Projections.ProjectionList()
                .Add(Projections.Property("Id"))
                .Add(Projections.Property("Numer")));

        var myList = criteria.SetResultTransformer(Transformers.AliasToEntityMap).List<Hashtable>();

        var myElement = myList[0]["Id"];

As far, as I have seen in the Internet, it should return list of dictionaries.

BUT: - myList contains 50 empty items - myElement is null.

What am I doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

The trick here is: conversion to key/value dictionary... requires alias.

Let's adjust the projection like this:

criteria.SetProjection(
        Projections.ProjectionList()          // Alias
            .Add(Projections.Property("Id")   .As("Id"))
            .Add(Projections.Property("Numer").As("Number"));

and the rest will work...