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?
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
}
session.CreateCriteria<Person>()
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToEntityMap)
.List<Hashtable>();
something like this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With