0
votes

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.

2
If you have the power change the identity to something that can be done by NHibernate for you (hilo, guid.comb, etc).anonymous
I don't see how that would fix the problem. The problem is that with the way the database tables are set up right now, the FKs on the table would never let one Job be saved without the Id of the other Job (which also isn't saved). So I think I need to change my database schema.Jon Kruger
Forgot about db constraints, sorry.anonymous

2 Answers

1
votes

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

0
votes

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.