user205892
user205892

Reputation: 311

NHibernate 1 to 0 or 1 to 1

I have a use case where my first entity "User" may or may not have "UserPreferences". So either there is no entry in UserPreferences table for a given user, or at max 1 entry.

Which kind of association should I use for modelling this? 1 to 1 or many to 1?

Thanks

Upvotes: 3

Views: 256

Answers (1)

Jakub Linhart
Jakub Linhart

Reputation: 4072

You could use many-to-one association. It's FNH mapping is straightforward:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        References(x => x.Preferences)
            .Cascade.All();
    }
}

Now Preferences property can be null but one user Preferences instance can be assigned to many instances of User. This can be handled on domain model side (e.g. see aggregate roots in DDD).

If you need a constraint on database side then it would be better to use one-to-one association (via primary key):

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        HasOne(x => x.Preferences)
            .Cascade.All();
    }
}

public class UserPreferencesMap : ClassMap<UserPreferences>
{
    public UserPreferencesMap()
    {
        Id(x => x.Id).GeneratedBy.Foreign("User");
        Map(x => x.Name);
        HasOne(x => x.User).Constrained();
    }
}

But it has some disadvantages. E.g. the association has to be bidirectional and all-delete-orphan is not supported...

Upvotes: 2

Related Questions