Get<T> NHibernate Entities by Property, Part 2

In the previous post, I showed how to use the Session.Get<T> syntax against an arbitrary property on the entity. The primary limitation with that method is that it only works for constant values. The following will work with constants, local variables, return values from methods, etc.

public static T Get<T>( this ISession session, Expression<Func<T, object>> expression )
{
    if( session == null ) throw new ArgumentNullException( "session" );

    var unary = expression.Body as UnaryExpression;
    if( unary == null )
        throw new FringineException( ErrorCodes.E_InvalidExpression );

    var operand = unary.Operand as BinaryExpression;
    if( operand == null )
        throw new FringineException( ErrorCodes.E_InvalidExpression );

    var member = operand.Left as MemberExpression;
    object value;
    if( operand.Right is ConstantExpression )
        value = ( (ConstantExpression) operand.Right ).Value;
    else
    {
        var lambda =
            Expression.Lambda<Func<object>>( Expression.Convert( operand.Right,
                                                                 typeof( object
                                                                    ) ) );

        var func = lambda.Compile();
        value = func();
    }

    return session.CreateCriteria( typeof( T ) )
        .Add( Restrictions.Eq( member.Member.Name, value ) )
        .UniqueResult<T>();
}

Now I can write statements like this:

var sku = Request["Sku"];
var product = Session.Get<Product>( x => x.Sku == sku );
var orLikeThis = Session.Get<Product>( x => x.Sku == Request[ "Sku" ] );

Related Articles

Published : Aug 10, 2009
Views : 3718

Subscribe Subscribe | Blog Home

Downloads

Tags

  • code
  • development
  • nhibernate