NHibernate One-To-One mapping using Mapping by Code

1.6k Views Asked by At

I have an class structure like this:

public class BaseEntity
{
    public Guid Id { get; set; }
}

// CREATE TABLE Project (Id, Name)
public class Project : BaseEntity
{
    public ProjectProperties Properties { get; set; }
    public string Name { get; set; }
}

// CREATE TABLE ProjectProperties (Id, Markup)
// ForeignKey from ProjectProperties.Id -> Project.Id
public class ProjectProperties  : BaseEntity
{
    public int Markup { get; set; }
}

What is the correct way to map this using NH 3.2 and Mapping By Code? I can't find examples where the 1:1 relationship is through the PKs.

2

There are 2 best solutions below

0
On

you can use Join since the primary keys match. it doesn't even need an own Id because it is dependant from Project

public class ProjectProperties
{
    public int Markup { get; set; }
}


// in ProjectMapping
Join("ProjectProperties", join =>
{
    join.Key("Id");
    join.Component(x => x.ProjectProperties, c =>
    {
        c.Property(x => x.Markup);
    }
});
0
On

I think you should use this code.

OneToOne(x => x.Properties,
           x => x.PropertyReference(typeof(ProjectProperties).GetProperty("Properties")));