Adding Unique Constraints to Fluent NHibernate Automapping Models

Fall back to fluent nhibernate and use the AutoMap<T>.SetAttribute() method. The following example ensures that no two users can ever have the same email address:

        private static AutoPersistenceModel Automapping()
        {
            return AutoPersistenceModel.MapEntitiesFromAssemblyOf<Entity>()                
                .ForTypesThatDeriveFrom<User>(map => {                     
                    map.Map(u => u.EmailAddress).SetAttribute("unique-key", "IX_Unique_EmailAddress");
                })                
                .Where(t => t.Namespace == "Myproject.Domain");
        }

Comments are closed