Get<T> NHibernate Entities by Property

While many of my entity classes use surrogate primary keys, they also have natural keys (Product SKU for example). When I want one of those entities it's more natural to use the natural key, naturally. Normally that requires a CreateCriteria call, I'd rather just call Get<T> like I can with the surrogate keys. So I created an extension method that lets me do this:

var product = session.Get<Product>( x => x.Sku == "DLX" );

And here's the extension method:

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;
    var operand = unary.Operand as BinaryExpression;
    var value = operand.Right as ConstantExpression;
    var member = operand.Left as MemberExpression; 

    return session.CreateCriteria( typeof( T ) )
        .Add( Restrictions.Eq( member.Member.Name, value.Value ) )


Related Articles

Published : Aug 07, 2009
Views : 8653

Subscribe Subscribe | Blog Home



  • code
  • development
  • nhibernate