Create your own Parts to merge Stored Procedure into Fluent NHibernate mappings

Update: This patch has been merged into Fluent NHibernate offiical release V1.1.

NOTE:  I created a patch to enable you can use stored procedure in RTM version (r647).   As they mentioned in FN google group, this patch has been merged into Fluent NHibernate trunk in November 2009, as the change log shown.

New syntax:

SqlInsert(INSERT_SP).Check.None();
SqlUpdate(UPDATE_SP).Check.None();
SqlDelete(DELETE_SP).Check.None();

Ryan’s solution is a very high level usage of Fluent NHibernate. By creating a customized StoredProcedurePart class implementing IMappingPart interface, developer gained some kind of control to merge their Stored Procedure definition into FN mappings.

A useful trick:

Export hbm file to somewhere say temp folder for debug purpose, you don’t trust any new guys.


            var config = Fluently.Configure()
                .Database(
                MsSqlConfiguration.MsSql2005
                    .ConnectionString(x => x.FromConnectionStringWithKey(connectionStringKey))
                    .ShowSql()
                    .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<T>()
                                   .ExportTo(Path.GetTempPath())
                )
                ;

I had to add sql-insert, sql-update, sql-delete into XmlHibernateMappingWriter.sorting Dictionary. The reason of applying this patch is: the current sorting xml children logic in FN (r479) has a bug when comparing two many undefined elements.

if (!sorting.ContainsKey(x.Name) || !sorting.ContainsKey(y.Name)) return 0;
e.g.
it was pre-defined that definded-element-A is less than definded-element-B, but if we introduced an un-defined-element-C,
ContainsKey check in sorting children method will say:
definded-element-A == un-defined-element-C,
and
un-defined-element-C ==definded-element-B,
this will result
definded-element-A == definded-element-B!

In my case, all the properties were bubbled up to first level and caused a strange System.Xml.Schema.XmlSchemaValidationException.

Note:  My patch doesn’t support sql-delete-all in array/primitive-array/bag/list/map/set/idbag yet, while they are defined in xsd file.

2 thoughts on “Create your own Parts to merge Stored Procedure into Fluent NHibernate mappings

Leave a comment