R – How to map two objects that reference each other in NHibernate

fluent-nhibernatenhibernate

I have a class that looks like this:

public class Job
{
    public Company Company {get;set;}
    public Job JobForCompanyA {get;set;}
    public Job JobForCompanyB {get;set;}
}

The jobs for the two companies will reference each other, for example:

var jobA = new Job { Company = Company.CompanyA };
var jobB = new Job { Company = Company.CompabyB };
jobA.JobForCompanyB = jobB;
jobB.JobForCompanyA = jobA;

The problem with this is that if I map these as normal many-to-ones in NHibernate, it can't save them… since each Job object references the other, you would have to save one to get the PK, but you can't because it references the other (unsaved) Job, so you have a chicken and egg problem.

From a db perspective, I could make a mapping table that maps Jobs for company A to Jobs for company B. Is there a way to map this using NHibernate without me having to change how my entity object looks? I know I could add list properties and hacks to do it like a normal many-to-many relationship, but this has to be a pattern that someone has a better solution for.

I'm using Fluent NHibernate, so you can give me solutions using Fluent NHibernate or NHibernate XML mappings.

Best Answer

This fluent mapping will allow you to reference multiple properties of the same type. Here I'm assuming that in your Job table you have two columns (JobAId and JobBId) that reference another Job (via JobId).

References(x => x. JobForCompanyA, "JobAId"); References(x => x. JobForCompanyB, "JobBId");

Related Topic