There are situations when you do not need to get the fully tracked entities using NHibernate — you know you wouldn’t ever edit them and need minimum overhead for this specific scenario. One example is AJAX auto-completion. On the other hand, if you are as obsessed with architectural purity as me, you probably do not have Id properties in your entities, since they are artefacts of (relational) DBs.

So there is the question: in UI layer we want to do

repository.Query().Select(x => new ListItem { Key = x.Id, Name = x.Name })

But there are no “Id” properties in our entities. How can we do this (without returning to the dark ages of untyped criteria)?

There is a very simple (and working) answer. Let’s start with how I do it for individual entities. When I need a key/id in the UI to identify the entity between requests, I use repository.GetKey(entity), which internally calls session.GetIdentifier(entity). Simple and not intrusive into domain logic. Now,

repository.Query().Select(x => new ListItem { Key = GetKey(x), Name = x.Name })

is obviously impossible, since HQL/DB can not understand GetKey call.

Ok, so the solution is to pre-process the call before Linq-to-NHibernate and replace GetKey call with reference to fake property named “id”, which is a magic name NHibernate understands as identifier reference. Linq-to-NHibernate even provides public expression visitor, so it was trivial to create KeyMethodToIdRewritingVisitor (the fake PropertyInfo took most effort, which had to have some stuff to fool Expression.Property).

You can get resulting code below.
It is not perfect, but it works and flaws are really easy to polish out.

  1. Repository
  2. KeyMethodToIdRewritingVisitor
  3. KeyEnabledQueryProvider

Recently I had a need for fuzzy search in one of my projects. Since I was using NHibernate, NHibernate.Search (Lucene.NET-based) seemed like a good choice. However, there was one limitation — NHSearch required custom attributes for its mapping.

That was suboptimal. I had to reference NHSearch from domain entities class, I had to add Id property to my entities to map NHSearch [DocumentId]. Fortunately, it was a free time project, so I decided to take a break from it and fix the NHSearch mapping.

Some days later, the patch was in NHSearch trunk.

So, while there are no new built-in mappings except the attribute one, it is now possible to create a mapping manually. Here is a simple sample mapping that indexes Title property of Book entity:

using NHibernate.Cfg;
using NHibernate.Engine;
using NHibernate.Properties;
using NHibernate.Search.Bridge;
using NHibernate.Search.Mapping;

internal class CustomSearchMapping : ISearchMapping {
    public ICollection<DocumentMapping> Build(Configuration cfg) {
        var bookMapping = new DocumentMapping(typeof(Book)) {
            DocumentId = new DocumentIdMapping("Id", BridgeFactory.INTEGER, null),
            Fields = { MapField<Book>(book => book.Title) }
        };

        return new List<DocumentMapping> { bookMapping };
    }

    private FieldMapping MapField<T>(Expression<Func<T, object>> propertyReference) {
        var property = (PropertyInfo)((MemberExpression)propertyReference.Body).Member;

        var getter = new BasicPropertyAccessor.BasicGetter(typeof(T), property, property.Name);
        var bridge = BridgeFactory.GuessType(property.Name, property.PropertyType, null, null);

        return new FieldMapping(property.Name, bridge, getter);
    }
}

That’s something that will hopefully get better in time (notice required call to BridgeFactory.GuessType with nulls, that one thing I haven’t yet got to fix).
But this works, and this does not require attributes (and this does not require reflection at all, actually, you can write your own IGetter with any kind of logic).

One more thing — the “Id” parameter to DocumentIdMapping is how the Id field will be named in index, not your identifier property name.
There is also additional parameter to DocumentIdMapping that specifies property name, but in most scenarios it should just work, even if the identifier is not mapped.

To enable this custom mapping, add the following to your nhsearch.cfg.xml or web.config:

<property name="hibernate.search.mapping">Sample.Repositories.CustomSearchMapping, Sample.Repositories</property>