Page 1 of 1

Custom Object Mapping with NHibernate

Posted: Wed Feb 18, 2015 3:56 pm
by efficiondave
I'm looking for a clean way to use NHibernate to map a custom table to a custom object without using the HBM XML files. I don't want to use the HBM XML files because I'm using a WSP project and it just seems a lot messier than it needs to be. NHibernate has extensions (Fluent and NHibernate.Mapping.Attributes) to make it easier but I haven't found an easy way to use those.

I've read http://wiki.ablecommerce.com/index.php/ ... _-_AC_Gold but there's nothing clean or good about having to create 9 separate files to incorporate a simple table.

I've read lots of helpful posts from Judy (jmestep) on using the NHibernateHelper but none of them address mapping to an object without HBM XML files.

Has anyone found a solution for this? We really could use better guidance from the Able folks on simple and clean options.

Re: Custom Object Mapping with NHibernate

Posted: Thu Feb 19, 2015 2:41 am
by jmestep
I did one object without mapping because it involved more than one table and the code was used in only a couple of places. (I do have quite a few other objects in the solution that have nHibernate mappings.)
Here is how I did it:
In a class in the App_Code folder:

Code: Select all

public class TradeGenericsResult
    {
        public string TradeName { get; set; }
        public string GenericName { get; set; }
        public string GenericResults { get; set; }
        public int GenericId { get; set; }
        public int TradeId { get; set; }
        public string TradeResults { get; set; }
        public string CrossReactant { get; set; }

    }
Then to call the object:

Code: Select all

IList<TradeGenericsResult> trades = new List<TradeGenericsResult>();
            string sql = "SELECT Trades.ID as TradeId, Trades.Name as TradeName, Trades.Generic_ID as GenericId, Generics.Name AS GenericName,Generics.Results as GenericResults FROM Trades RIGHT OUTER JOIN Generics ON Trades.Generic_ID = Generics.ID WHERE (Trades.Generic_ID <> 0) ORDER BY Trades.Name ";
            ISQLQuery query = NHibernateHelper.CreateSQLQuery(sql); query.SetResultTransformer(Transformers.AliasToBean(typeof(TradeGenericsResult)));
            trades = query.List<TradeGenericsResult>();
I don't have any insert, update, or delete routines because that is done using the two other custom objects that are mapped.

I like using nHibernate, especially after having to go back and create some custom classes in AC7, but sometimes I can spend hours debugging the mapping, even with a mapping code generator I have found. Right now I've got 5 objects that mapped fine with it, but one that just does not work. Here is the generator, in case you are interested. It makes the mapping file and the class file so you need to add a datasource class.
https://nmg.codeplex.com/