I'm struggling to find the best way to model 1 : 0,1 relationships ("may have one" or "has at most one"). I believe this is called Z cardinality.
For example, suppose I have two classes Widget
and WidgetTest
. Not all Widgets are tested and the test is destructive so there can be at most one WidgetTest per Widget. Also assume that it's inappropriate to add the WidgetTest fields to Widget.
I would like my public interface to be:
Widget
WidgetTest { get; set; }
WidgetTest
Widget { get; }
Model 1: Widget has a WidgetTest property and in the database the Widget table has a uniquely constrained foreign key to WidgetTest. My DBA argues that this would allow a WidgetTest record to exist without a Widget.
WidgetTable
WidgetTestId (FK, UQ)
Model 2: Widget has a private collection of WidgetTest and enforces the 0,1 relationship by adding or removing a single object from the collection controlled by a public WidgetTest property. The database models this as 1:m with WidgetTest having a uniquely constrained foreign key to Widget. I argue that this means adopting the model to fit the database schema (i.e. more work for me).
WidgetTestTable
WidgetId (FK, UQ)
Which model is better? Which is easier to achieve with NHibernate? Or is there a third way?
Edit ... Here's what I ended up with:
public class Widget
{
// This is mapped in NH using a access strategy
private IList<WidgetTest> _widgetTests = new List<WidgetTest>(1);
public WidgetTest
{
get { return _widgetTests.FirstOrDefault(); }
set
{
_widgetTests.Clear();
if (value != null)
{
_widgetTests.Add(value);
}
}
}
}