Search code examples
c#nhibernateormunique-constraintnhibernate-mapping-by-code

NHibernate mapping by code - composite unique index


How do I create a composite UNIQUE constaint on 3 properties of a class? It needs to allow NULL as a legitimate value.


Solution

  • This should be one of the ways to go about it..

            mapper.Class<MyClass>(ca =>
                {
                    ca.Property(x => x.Property1, map => map.UniqueKey("UQ_ComposedUniqueKey"));
                    ca.ManyToOne(x => x.FKField1, map => { map.UniqueKey("UQ_ComposedUniqueKey"); map.NotNullable(false); });
                });
    

    You can combine many properties or FKs in a single unique key.