So I have following entities:
TimelineRecord:
ID: PK
From: DateTime
To: DateTime
ServiceRecord extends TimelineRecord:
ID: PK
TimelineRecord_ID: FK
SomeSpecificProperties...
Demand:
ID: PK
From: DateTime
To: DateTime
...
ServiceDemandConnection:
ID: PK
Service: ServiceRecord
Demand: Demand
TimelineRecord, Demand and ServiceDemandConnection are mapped using ClassMap with Id(x => x.Id). ServiceRecord is mapped using SubclassMap (table-per-class). References in ServiceDemandConnection are mapped using References(x => x.Service).Cascade.None() and the same for .Demand.
The problem is with inserting ServiceDemandConnection with properly set ServiceRecord and Demand. I get an error: Detail=Key (servicerecord_id)=(8) is not present in table "ServiceRecord". What error states is true. 8 is the ID of TimelineRecord, not ServiceRecord. However, ID of ServiceRecord (TimelineRecord_ID, which is actually not mapped/not accessible in the code) should be used instead. The current mapping hides ServiceRecord.ID.
How should I tell NHibernate to use ID of the subclass table (ServiceRecord), and not of the base class table (TimelineRecord)? NHibernate actually creates a proper constraint in the database, but during runtime it violates it somehow.
You need to either
ServiceRecord
as separate class not using SubclassMap
to use it's ID
ID
from base class and do not map it inside SubclassMap
The second approach works because SubclassMap
creates a FK
relationship between child and parent object so that data is consistent and you have something like
TimeLineRecord
ID : PK
ServiceRecord extends TimelineRecord:
TimelineRecord_ID: FK -----> TimeLineRecord.ID
It is still valid to point references to child classess.