Search code examples
nhibernatefluent-nhibernatefluent-nhibernate-mapping

Fluent NHibernate Conventions : OptimisticLock.Is(x => x.Version()) doesn't work


I am having problems with using OptimisticLock as a Convention. However, using OptimisticLock within Individual ClassMap's works fine. It throws Stale State Object Exceptions.

Each Class corresponding to a Table in the database has a property (which corresponds to a Column in the Table) of type DateTime which I am trying to use for Locking using OptimisticLock.Version().

It works only when I use it within every ClassMap, I don't want to write so many ClassMaps, I instead want to use Auto Mapping.

It WORKS like this within the Class Map

Version(x => x.UpdTs).Column("UPD_TS"); OptimisticLock.Version();

So, I started using Convention below, but it DOESN'T WORK.

OptimisticLock.IsAny(x => x.Version());

I tried setting the DynamicUpdate, etc. Nothing seems to work for me. Please help !


Solution

  • Here's what I did to get it work using a Convention :

    /// <summary>
    /// Class represents the Convention which defines which Property/Column serves as a part of the Optimistic Locking Mechanism.
    /// </summary>
    public class VersionConvention : IVersionConvention, IVersionConventionAcceptance
    {
        public void Accept(IAcceptanceCriteria<IVersionInspector> criteria)
        {
            criteria.Expect(x => x.Name == "%COLUMN_NAME%");
        }
    
        /// <summary>
        /// Method applies additional overrides to the <see cref="IVersionInstance"/>
        /// </summary>
        /// <param name="instance"><see cref="IVersionInstance"/></param>
        public void Apply(IVersionInstance instance)
        {            
            instance.Column("%COLUMN_NAME%");
        }
    }
    

    %COLUMN_NAME% above is the Property being used for Locking using Version.

    Then specified that the Version should be used for Optimistic Locking, when creating a FluentConfiguration Object, like this

    OptimisticLock.Is(x => x.Version();