开发者

NHibernate 1 to 0 or 1 to 1

开发者 https://www.devze.com 2023-03-06 11:46 出处:网络
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.

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 开发者_StackOverflow中文版1 or many to 1?

Thanks


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消