I am new to NHibernate and not sure how to map a ZeroToOne
relationship:
There are 3 tables involved
Discounts
DiscountRequests
Requests
The primary keys of both are stored as a pairs in DiscountRequests
, not all discounts have a request and not all requests have a discount.
Each primary key only appears once in DiscountRequests
so Discount
has a one to one relationship to DiscountRequests
and that is the same for Requests
.
Anyone have any idea how to map this so a Discount object can hold a reference to it request if it has one and a Request object holds a reference to a Discount if it has one. Otherwise they will hold a null object.
This is an interesting case of relationship as it is not a classical one-to-one - you don't have one side that is an owner of the relationship. This means you have to have an indirect "many-to-many" table, as in your example. The simplest solution is to map it as collections in NHibernate, but that's weird if in your domain you can't have more than one item there.
But there are joins to help. Join mapping allows you to split one entity into several database tables in a way that is transparent to your domain objects. Now you can have something like this in your Discount
mapping:
<join table="DiscountRequests" optional="true">
<key column="DiscountId" />
<many-to-one name="Request" column="RequestId" />
</join>
And similar one on the Request
side:
<join table="DiscountRequests" optional="true">
<key column="RequestId" />
<many-to-one name="Discount" column="DiscountId" />
</join>
Effectively, it's like the DiscountRequests
table was split to two and references to Request
went to Discount
object and other way round respectively.
Remember to have unique constraints on both RequestId
and DiscountId
so that there's no chance there will be more than one row joined.
I would also check there are no ill effects on saves and updates with the profiler, but I don't expect any.