In most circumstances, you will use a many-to-one mapping and that’s easily created with fluent nHibernate using the “References” relationship. However if you need to perform a 1 to 1 mapping, then things get tricky. Say for example, you have a user record and wanted to have the user preferences in another table. Each user will have a record in the preferences table so it’s a direct one to one mapping. You will then have to use the HasOne relationship in fluent nhibernate.
public class User { public virtual int Id { get; set; } public virtual string Username { get; set; } public virtual UserPreference Preference { get; set; } } public class UserMap : ClassMap<User> { public UserMap() { Id(x => x.Id); Map(x => x.Username); HasOne(x => x.Preference); } } public class UserPreference { public virtual int UserId { get; set; } public virtual bool Newsletter { get; set; } } public class UserPreferenceMap : ClassMap<UserPreference> { public UserPreferenceMap() { Id(x => x.UserId).GeneratedBy.Assigned(); Map(x => x.Newsletter); } }
So we have a User table with Id set as the primary key and we have a second table UserPreference with UserId as the primary key. The Id on the user table is autogenerated by the database but when a user entity has already been created, we pass this object to the UserPreference entity so that it can get the UserId. That’s why we need to specify in the mapping class for UserPreferenceMap that the Id is Assigned.