Foreign Key Constraint is preventing NHibernate from saving child record


I have two tables:





With a foreign key constraint so I don't have any unassociated Notes…in sql that constraint is working properly.

On my SupportTicket class I have an IList SupportTicketNotes property and have it mapped as a bag (probably really should be a set but that's not important at the moment). The load works just fine. The problem is if I new up a SupportTicket, new up a SupportTicketNote, add the note to the ticket and save the ticket. NHibernate is inserting the SupportTicket, then inserting the SupportTicketNote with a SupportTicketID of zero which blows up of course because of the FK constraint. If I delete the constraint it will insert with the SupportTicketID of zero and then go back and do an update on the SupportTicketNote with the proper ID value…but that seems….wrong. Is there anything I might be doing in the mapping that is causing that?

UPDATED to include Many to One mapping on child object

Here's my current mapping for SupportTicket:

<bag name="_supportTicketNotes" table="SupportTicketNotes" access="field" cascade="save-update" inverse="true" >
  <key column="SupportTicketID" foreign-key="FK_SupportTicketNotes_supporttickets" ></key>
  <one-to-many class="NhibernateSample.DomainModel.SupportTicketNote, NhibernateSample.DomainModel" />

Here is my mapping for SupportTicketNote (note my SupportTicketNote class has both the SupportTicketID and SupportTicket object properties):

 <many-to-one name="SupportTicket"   class="NhibernateSample.DomainModel.SupportTicket, NhibernateSample.DomainModel"   column="SupportTicketId" cascade="all"/>  

Best Solution

I haven't seen your full mapping, but the first thing that pops into my head is this section from the documentation:

Very Important Note: If the <key> column of a <one-to-many> association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.

Related Question