In our project, we’re sub classing multiple domain classes from a single Reference Data table – i.e. Volume and Weight types. Among other things, the reference data table contains discriminator, code and value columns. The ‘discriminator’ column stores the name of the class and is used by Fluent NHibernate to determine which subclass to instantiate, the ‘value’ column is the full name of the reference data item, and the ‘code’ column is the abbreviated version of the value.

The code and value together are unique, and a composite key is created containing them both.

We load in reference data from an excel spreadsheet, and at some point, there was a code and value pair added to a reference data type which matched exactly with a code and value pair from another reference data type. Attempting to add the second code value pair resulted in a unique key violation.

I needed to add the discriminator column into the composite key. If you’re using auto mapping, you’ll need to add an auto mapping override. Below is an example of creating a composite key containing the code, discriminator and value columns.

public class ReferenceDataAutoMappingOverride : IAutoMappingOverride<ReferenceData>
 public void Override(AutoMapping<ReferenceData> mapping)
 const string uniqueKeyName = "UK_ReferenceData_discriminator_Code_Value";

 mapping.Map(refData => refData.Code).UniqueKey(uniqueKeyName);
 mapping.Map(refData => refData.Value).UniqueKey(uniqueKeyName);