I have a bidirectional association like this:
public class Parent
{
public int ParentId {get; set;}
...other properties
public IEnumerable<Child> Children {get; set;}
}
public class Child
{
public int ChildId {get; set;}
...other properties
public Parent Parent {get; set;}
}
The fluent mappings are as follows:
Parent mapping
Id(x => x.ParentId, "PARENT_ID").GeneratedBy.Identity();
.. other mappings
HasMany(x => x.Children).Cascade.All().KeyColumn("PARENT_ID");
Child mapping
Id(x => x.ChildId, "CHILD_ID").GeneratedBy.Identity();
.. other mappings
References(x => x.Parent).Column("PARENT_ID").Cascade.None();
When I execute code like this:
Parent parent = new Parent{ ..set some properties... };
parent.Children = new[] { new Child{ ..set some properties.. };
session.Save(parent);
I get a foreign key constraint violation because NHibernate is not setting the PARENT_ID
column of the child record to the new ID when it attempts to insert the child.
Clearly I have requested cascading in the mapping for Parent
. NHibernate is trying to save the child, but why is the ID not being set?