NHibernate One to One mapping

After a lot of trial and error i finally found a good solution to my one-to-one mapping situation

Posted by Carl Berg on Mon, Apr 27, 2015 | Tags nhibernate, fluent nhibernate

A working One to One mapping in NHibernate (using FluentNHibernate for this example):

public class NotificationMap : ClassMap<Notification>
    public NotificationMap() 
        Id(x => x.Id); 
        HasOne(x => x.Trigger).PropertyRef(x => x.Notification).Cascade.All();
CREATE TABLE [dbo].[Notification]( [Id] [uniqueidentifier] NOT NULL ) 
public class NotificationTriggerMap : ClassMap<NotificationTrigger> {
    public NotificationTriggerMap() 
        Id(x => x.Id); 
        References(x => x.Notification).Not.Nullable(); 
CREATE TABLE [dbo].[NotificationTrigger]( 
    [Id] [uniqueidentifier] NOT NULL, 
    [NotificationId] [uniqueidentifier] NOT NULL ) 

ALTER TABLE [dbo].[NotificationTrigger] 
    WITH NOCHECK ADD CONSTRAINT [FK_NotificationTrigger_NotificationId_Notification_Id] 
    FOREIGN KEY([NotificationId]) 
    REFERENCES [dbo].[Notification] ([Id])
var notification = new Notification();
var trigger = new NotificationTrigger { Notification = notification };
notification.Trigger = trigger;
session.Flush(); //Will create both entities in the database