Search code examples
c#nhibernatenhibernate-mapping

Nhibernate : Map all decimals with the same precision and scale


I understand that in NHibernate, using mapping by code, I can specify the precision and scale of a decimal property like so:

Property(
    x => x.Dollars,
    m =>
        {
            m.Precision(9);
            m.Scale(6);
        }
 );

That is nice, but I was wondering if there was a way that I could easily map ALL of the decimal properties in all of the classes in an easy way. It seems kind of crazy that I would have to go through all of my mappings and update each of them by hand. Does anyone know how this can be achieved ?


Solution

  • Use the BeforeMapProperty on the ModelMapper:-

    var mapper = new ModelMapper();
    
    mapper.BeforeMapProperty += (inspector, member, customizer) =>  {
        if (member.LocalMember.GetPropertyOrFieldType() == typeof (decimal))
        {
          customizer.Precision(9);
          customizer.Scale(6);
        }
    };
    

    The only other thing to add is remove all occurrences of:-

     m => { m.Precision(9); m.Scale(6); }
    

    from your mapping classes as these will override your convention set in BeforeMapProperty unless you have other decimals that have different scales or precisions.