Monday, December 20, 2010

Using Fluent NHibernate in SharePoint 2010

Most of the time when developing with SharePoint 2010 we don’t have to use any ORM mapping because SharePoint’s API take care of 99% of our needs. Today I had to use Business Connectivity Services to expose data in a third party database as External List.

When defining Business Connectivity Model in SharePoint project we have to write (at least) our own ReadList and ReadItem methods.

My implementation of ReadList and ReadItem were pretty simple:

        public static MyEntity ReadItem(string id)
        {
            var session = SessionSource.Current.GetSession();
            var repository = new Repository<MyEntity>(session);

            return repository.GetById(id).ToEntity();
        }

        public static IEnumerable<MyEntity> ReadList()
        {
            var session = SessionSource.Current.GetSession();
            var repository = new Repository<DomainObject>(session);
            var results = repository.ListAll();
            return results.Select(x => x.ToEntity()).ToList();
        }

Those 2 methods worked fine in the Unit Test. However (as usual) when running in SharePoint’s environment they fell apart.
After a lot of hours in debugging finally I managed to make they work.

These are a few things you might want to check when using Fluent NHibernate with SharePoint 2010:

1. Make sure you include ALL dlls which came with Fluent NHibernate in the package with GlobalAssemblyCache as the target deployment (Business Connectivity Model will have to be deployed as a farm solution).














2. Add qualifyAssembly tags for all those dlls to your web config to tell NHibernate to load those assemblies from the GAC instead of the bin folder.







After completing those 2 steps my ReadList and ReadItem work as expected J
Hope this helps J

1 comment: