Search code examples
nhibernatefluent-nhibernate

Is it possible for nhibernate to return a query as an IDictionary instead of an entity class?


I have an entity Person:

public class Person
{
   public virtual int Id {get; set; }
   public virtual string FirstName { get; set; }
   public virtual string MiddleName { get; set; }
   public virtual string LastName { get; set; }
}

with the mappings:

public class PersonMap
{
   public PersonMap()
   {
       Table(TABLE_NAME); 
       Id( x => x.Id);
       Map(x => x.FirstName).Not.Nullable();
       Map(x => x.LastName).Not.Nullable();
       Map(x => x.MiddleName).Not.Nullable();
    }
}

There are some stuations where I would like Nhibernate to return a dictionary instead of the entity:

IDictionary<string,string> person = session.Get(id);//????
string firstName = person["FirstName"];

Is this possible to without adding a different mapping?


Solution

  • You will need to define your own ResultTransformer implementation to have this working the way you need it. Below is a reference implementation that you can tweak as needed. There is a complete lack of error-checking, etc; so use with caution ;)

    using System;
    using System.Collections;
    using NHibernate;
    using NHibernate.Properties;
    using NHibernate.Transform;
    
    
    [Serializable]
    public class DictionaryResultTransformer : IResultTransformer
    {
    
            public DictionaryResultTransformer()
            {
    
            }
    
            #region IResultTransformer Members
    
            public IList TransformList(IList collection)
            {
                    return collection;
            }
    
            public object TransformTuple(object[] tuple, string[] aliases)
            {
              var result = new Dictionary<string,object>();
              for (int i = 0; i < aliases.Length; i++)
              {
                result[aliases[i]] = tuple[i];                         
              }
              return result;
            }
    
            #endregion
    }