views:

91

answers:

2

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.

+1  A: 

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");

wgpubs
That's what I have now, but it leads to the chicken-and-egg problem where one Job can't be saved until the other is saved, but since they both reference each other neither can be saved.
Jon Kruger
Jon,I think you need to persist jobA and jobB BEFORE creating the association. This will result in multiple hits on the database but will give you the desired result. The mapping presented here is correct.
wgpubs
A: 

I don't see how to do it without creating another entity with none of these references so you can get null values saved. Save two of these dummy entities and grab their ids. Then retrieve each of them using their ids through the Job entity you already have and set them to each other that way. You should be able to save then.

It's ugly but that's pretty much how you'd have to do it in SQL anyway. I'd think about coming up with a different pattern if I were you.

Spencer Ruport