NHibernate 1 to 0 or 1 to 1

I have a use case where my first User object may or may not have UserPreferences. Thus, either there is no entry in the UserPreferences table for this user, or in max. 1 entry.

What association should I use to model this? 1 to 1 or a few to 1?

thank

+3
source share
1 answer

You can use the many-to-one association. This FNH mapping is simple:

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

Now the Preferences property can be null, but a single instance of a user's Preferences can be assigned to many instances of User. This can be handled on the domain model side (for example, see Aggregate Roots in DDD).

, - ( ):

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();
    }
}

. . , -- ...

+2

All Articles