Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

29 September 2009

Inheritance and NHibernate.Search

I recently ran into a problem using NHibernate.Search. It is not possible to query properties of a derived class if NHibernate.Search only has access to it through a base class.
I used to have:
  [IndexedEmbedded]
  public virtual FieldType FieldType
  {
      get;
      set;
  }
The FieldType class is an abstract class from which concrete implementations derive. I wanted to index the properties of several derived classes, for example the OtherFieldType class:
public class OtherFieldType : FieldType {
  [Field]
  public virtual string Name {
      get;
      set;
  }
}
In this example, querying NHibernate.Search with "FieldType.Name:something" won't return any results. Apparently NHibernate.Search does not know it should query the concrete class implementation, OtherFieldType, for this query.

The workaround for this is to remove the IndexedEmbedded attribute from the base property and include a private field dedicated for NHibernate.Search to index and query. The private field does hold the concrete implementation:
  public virtual FieldType FieldType
  {
      get;
      set;
  }

  [IndexedEmbedded]
  private OtherFieldType OtherFieldType
  {
      get
      {
          return FieldType as OtherFieldType;
      }
  }
In this way, NHibernate.Search will know how to index and search the embedded properties. The query "OtherFieldType.Name:something" will now return the correct results.

No comments: