Search code examples
c#nhibernatefluent-nhibernatenhibernate-mappingqueryover

Fluent NHibernate - column name from property in Session.QueryOver


I have a Session.QueryOver, that I need to mantain, and I want to remove the magical strings for column names, something like:


return Session.QueryOver<T>()
    .SelectList(list => list
        .Select(Projections.SqlGroupProjection(
            "CANDIES(" + MagicalStringForColumnName +") As [Candies]",
            "CANDIES(" + MagicalStringForColumnName + ")",
            new[] { "Candies" },
            new IType[] { NHibernateUtil.Int32 }))

And I want it to be like:

return Session.QueryOver<T>()
    .SelectList(list => list
        .Select(Projections.SqlGroupProjection(
            "CANDIES(" + Session.GetColumnNameFromMappedProperty(propInfo.Name) +") As [Candies]",
            "CANDIES(" + Session.GetColumnNameFromMappedProperty(propInfo.Name) + ")",
            new[] { "Candies" },
            new IType[] { NHibernateUtil.Int32 }))

Solution

  • Turns out, that with the use of alias and SqlFunction, one can use an expression, instead of a magical string.

            object a = null;
    
            return Session.QueryOver<T>()
                   .SelectList(l =>
                       l.Select(
                       Projections.GroupProperty(
                       Projections.SqlFunction("CANDIES", NHibernateUtil.Int32, Projections.Property(expression))
                       )).WithAlias(() => a)