Deleting by ID (or primary key) with Fluent NHibernate

I wasn't a big fan of so-called Fluent Interfaces but my fondness is growing as I use Fluent NHibernate on an ASP.NET MVC project. When I started on my project I checked out the repository pattern example from Google Code to see how this was being im­ple­ment­ed. The supplied repository interface provided the following interface:

public interface IRepository
    T Get(object id);
    void Save(T value);
    void Update(T value);
    void Delete(T value);
    IList GetAll();

Looks great apart from the fact that you need to pass an entity to the Delete() method, which would in turn result in iteration over a large number of objects if I had to do a lot of deletes. If I received an integer with an ID from an ASP.NET MVC controller I'd have to retrieve the object before sending it to the Delete() method. This is not very efficient.

To remedy this problem I added an additional Delete() method to the interface taking an object ID as the only parameter:

public void Delete(object id)
    using (var session = sessionFactory.OpenSession())
    using (var transaction = session.BeginTransaction())
        var queryString = string.Format("delete {0} where id = :id", typeof(TEntity));
               .SetParameter("id", id)


This is a very simple method that will generate more efficient SQL under the covers for deletion of objects from the database.

Tagged with databases, fluent-nhibernate, nhibernate and orm.