Search code examples
sqlnhibernatefluent-nhibernateuniqueunique-constraint

Fluent NHibernate: unique column that allows multiple NULL values


I've got a column in a table that needs to be unique when a value is present, but should allow multiple NULL values. In SQL, I can do this using this answer, but is there a way to configure this using Fluent NHibernate?

            Map(x => x.UniqueProperty).Unique().Nullable();

...does not work, and creates an unfiltered unique constraint that does not allow multiple NULL values.


Solution

  • You cannot do that in NHibernate, that is, NHibernate won't let you create this kind of constraint. Yes, it is possible, for example, in SQL Server, if you create a unique index which does not apply to NULLS:

    CREATE UNIQUE INDEX idx_UniqueProperty_notnull
    ON dbo.T1(UniqueProperty)
    WHERE UniquePropertyIS NOT NULL;