Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
wusher Avatar asked Sep 03 '10 17:09

wusher


2 Answers

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
}
like image 126
DanP Avatar answered Oct 27 '22 20:10

DanP


session.CreateCriteria<Person>()
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToEntityMap) 
.List<Hashtable>();

something like this?

like image 27
Wayne Avatar answered Oct 27 '22 19:10

Wayne