I'm trying to use the alias to bean method to map custom sql into a
dto, but because I want to map from a column that has 1's and 0's to a
boolean it fails.
I have implemented my own one and it seems to work. Is there a better
way?
[Serializable]
public class MyAliasToBeanResultTransformer :
IResultTransformer
{
private const BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance;
private readonly System.Type resultClass;
private object[] setters;
private readonly IPropertyAccessor propertyAccessor;
private readonly ConstructorInfo constructor;
public MyAliasToBeanResultTransformer(System.Type
resultClass)
{
if (resultClass == null)
{
throw new ArgumentNullException("resultClass");
}
this.resultClass = resultClass;
constructor = resultClass.GetConstructor(flags, null,
System.Type.EmptyTypes, null);
// if resultClass is a ValueType (struct),
GetConstructor will return null...
// in that case, we'll use Activator.CreateInstance
instead of the ConstructorInfo to create instances
if (constructor == null && resultClass.IsClass)
{
throw new ArgumentException("The target class of a
AliasToBeanResultTransformer need a parameter-less constructor",
"resultClass");
}
propertyAccessor =
new ChainedPropertyAccessor(new[]
{
PropertyAccessorFactory.GetPropertyAccessor(null),
PropertyAccessorFactory.GetPropertyAccessor("field")
});
}
public object TransformTuple(object[] tuple, String[]
aliases)
{
object result;
try
{
if (setters == null)
{
setters = new object[aliases.Length];
for (int i = 0; i < aliases.Length; i++)
{
string alias = aliases[i];
if (alias != null)
{
setters[i] = new object[]
{
propertyAccessor.GetSetter(resultClass, alias),
propertyAccessor.GetGetter(resultClass, alias).ReturnType
};
};
}
}
// if resultClass is not a class but a value type,
we need to use Activator.CreateInstance
result = resultClass.IsClass
? constructor.Invoke(null)
:
NHibernate.Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(resultClass,
true);
for (int i = 0; i < aliases.Length; i++)
{
if (setters[i] != null)
{
var type = (Type)((object[]) setters[i])
[1];
var setter = (ISetter)((object[])
setters[i])[0];
if (!
type.IsAssignableFrom(tuple[i].GetType()))
setter.Set(result,
Convert.ChangeType(tuple[i], type));
else
setter.Set(result, tuple[i]);
}
}
}
catch (InstantiationException e)
{
throw new HibernateException("Could not
instantiate result class: " + resultClass.FullName, e);
}
catch (MethodAccessException e)
{
throw new HibernateException("Could not
instantiate result class: " + resultClass.FullName, e);
}
return result;
}
public IList TransformList(IList collection)
{
return collection;
}
}
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/nhusers?hl=en.