I use the new Projection support and a result transformer. Nice part about this is it works nice with Ayende's Rhino-Commons and NHQG. Also, there is no overhead like some of the other examples of hydrating entities. The sql generated selects just the two columns for Name and Value and there are no random joins caused from lazy loading settings.
Code:
public class DropDownDTO<NameType, ValueType>
{
public static IList<DropDownDTO<NameType, ValueType>> List(ISession session, Type type, string nameProperty)
{
return List(session, type, nameProperty, null, false);
}
public static IList<DropDownDTO<NameType, ValueType>> List(ISession session, Type type, string nameProperty, string valueProperty)
{
return List(session, type, nameProperty, valueProperty, false);
}
public static IList<DropDownDTO<NameType, ValueType>> List(ISession session, Type type, string nameProperty, string valueProperty, bool distinct)
{
ICriteria c = session.CreateCriteria(type);
ProjectionList pl = Projections.ProjectionList();
if (string.IsNullOrEmpty(valueProperty))
pl.Add(Projections.Id());
else
pl.Add(Projections.Property(valueProperty));
pl.Add(Projections.Property(nameProperty));
if (distinct)
c.SetProjection(Projections.Distinct(pl));
else
c.SetProjection(pl);
c.SetResultTransformer(new NHibernate.Transform.AliasToBeanConstructorResultTransformer(
typeof(DropDownDTO<NameType, ValueType>).GetConstructors()[0]));
return c.List<DropDownDTO<NameType, ValueType>>();
}
public DropDownDTO(ValueType value, NameType name)
{
_name = name;
_value = value;
}
public NameType Name { get { return _name; } } NameType _name;
public ValueType Value { get { return _value; } } ValueType _value;
}
public void Page_Load(object sender, EventArgs args)
{
ddl.DataSource = DropDownDTO<String, Int32>.List(_session, typeof(Contact), "DisplayName");
ddl.NameField = "Name";
ddl.ValueField = "Value";
}
Adam