Search code examples
nhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mappingsharp-architecture

Multiple UniqueKeys in Fluent NHibernate


I've got a scenario where I need to define two multicolumn unique constraints like so:

public class UserMap : IAutoMappingOverride<User>
{
    public void Override(AutoMapping<User> mapping)
    {
        mapping.Map(x => x.UserName)
               .UniqueKey("UQ_User_UserName_Client");
        mapping.Map(x => x.LoweredEmail)
               .UniqueKey("UQ_User_Email_Client");
        mapping.References(x => x.Client)
               .UniqueKey("UQ_User_UserName_Client")
               .UniqueKey("UQ_User_Email_Client");
    }
}

The reason for this is I need both the UserName and the Email to be unique for each client. The resulting SQL looks like this:

create table Users (
   Id UNIQUEIDENTIFIER not null,
   UserName NVARCHAR(256) not null,
   LoweredEmail NVARCHAR(256) not null,
   Email NVARCHAR(256) not null,
   ClientId UNIQUEIDENTIFIER null,
   primary key (Id),
   unique (UserName),
   unique (LoweredEmail, ClientId)
)

Which is not the desired effect. How do I get the following SQL to be created?

create table Users (
   Id UNIQUEIDENTIFIER not null,
   UserName NVARCHAR(256) not null,
   LoweredEmail NVARCHAR(256) not null,
   Email NVARCHAR(256) not null,
   ClientId UNIQUEIDENTIFIER null,
   primary key (Id),
   unique (UserName, ClientId),
   unique (LoweredEmail, ClientId)
)

I'm not sure if this is an issue/limitation with Fluent or NHibernate. Any help would be appreciated.


Solution

  • Calling UniqueKey multiple times overrides the previous value.

    Instead, use a comma-separated list of unique keys:

    mapping.Map(x => x.UserName)
           .UniqueKey("UQ_User_UserName_Client");
    mapping.Map(x => x.LoweredEmail)
           .UniqueKey("UQ_User_Email_Client");
    mapping.References(x => x.Client)
           .UniqueKey("UQ_User_UserName_Client, UQ_User_Email_Client")