Search code examples
nhibernatefluent-nhibernatenhibernate-mapping

How do I map an optional one-to-one relationship with Fluent NHibernate?


I've got two entities, one called Site and the other called Assignment. A Site may or may not have an associated Assignment. An Assignment is only ever associated with one Site. In terms of C#, Site has a property of type Assignment which could hold a null reference.

I have got two tables by the same names in the database. The Assignment table's PK is also its FK back to the Site table (rather than Site having a nullable FK pointing to Assignment). The SQL (with fields omitted for brevity) is as follows

CREATE TABLE Site(
    SiteId INT NOT NULL CONSTRAINT PK_Site PRIMARY KEY)

CREATE TABLE Assignment(
    AssignmentId INT NOT NULL CONSTRAINT PK_Assignment PRIMARY KEY,
    CONSTRAINT FK_Assignment_Site FOREIGN KEY (AssignmentId) REFERENCES Site (SiteId))

I'm using Fluent NHibernate's auto persistence model, which I think I will have to add an override to in order to get this to work. My question is, how do I map this relationship? Is my schema even correct for this scenario? I can change the schema if needs be.


Solution

  • You need to read these:

    it's not possible to have one-to-ones lazy loaded unless they are not-nullable, or you map them as a many-to-one with one item in it