Strongly type properties with NHibernate
I like NHIbernate and use it in all my projects. Now I am working on Atomic CMS – its a content management system project. I am working on sorting, but I don’t like to use strings for names of properties. I tried to find solution how to use strongly typed properties with NHibernate, but did not. So I created my own solution.
Instead of the code like this
session.CreateCriteria(typeof(IEntry)).AddOrder(Order.Desc("Alias"))
I prefer to have something like this
session.CreateCriteria(typeof(IEntry)).AddOrder(Order.Desc(x=>x.Alias))
But unfortunately it’s not possible with NHibernate. So I created simple solution which is fine for me and my project. I created class to return name of the method or property. The code using this class looks like this
session.CreateCriteria(typeof(IEntry)).AddOrder(Order.Desc(Strong<IEntry>.Name(x=>x.Alias)))
And the code for Strong class is.
namespace AtomicCms.Common.Utils
{
using System;
using System.Linq.Expressions;
public static class Strong<T>
{
public static string Name(Expression<Func<T, object>> action)
{
if (null == action || null == action.Body)
{
throw new NullReferenceException("action or action.body is null");
}
UnaryExpression unary = action.Body as UnaryExpression;
if (null != unary && null != unary.Operand as MemberExpression)
{
return PropertyName(unary.Operand);
}
MemberExpression memberCall = action.Body as MemberExpression;
if (memberCall != null)
{
return PropertyName(action.Body);
}
MethodCallExpression methodCall = action.Body as MethodCallExpression;
if (null != methodCall)
{
return MethodName(action.Body);
}
throw new Exception("Not supported action " + action);
}
private static string PropertyName(Expression operand)
{
MemberExpression member = operand as MemberExpression;
if (member != null) return member.Member.Name;
throw new NullReferenceException("Unxexpected null reference");
}
private static string MethodName(Expression operand)
{
MethodCallExpression member = operand as MethodCallExpression;
if (member != null) return member.Method.Name;
throw new NullReferenceException("Unxexpected null reference");
}
}
}
Tags: nHibernate
Trackback from your site.
