I have two entities:
public class Parent()
{
public ICollection<Child> Children { get; set; }
}
public class Child()
{
public Parent Parent { get; set; }
}
The mapping looks like so:
public class ParentMap : ClassMap<Parent>
{
HasMany(x => x.Children).Cascade.All().Inverse();
}
public class ChildMap : ClassMap<Child>
{
References(x => x.Parent).Cascade.None();
}
Normally, in order to save a parent or a child, you'd have to do something like this:
var parent = new Parent();
var child = new Child();
parent.Children.Add(child);
child.Parent = parent;
Session.SaveOrUpdate(parent);
In other words, you have to set the properties in both objects in order for NHibernate to persist this entity correctly.
However, for legacy issues, I'd like to save this entity without having to set both sides, so that I can just do:
var parent = new Parent();
var child = new Child();
child.Parent = parent;
Session.SaveOrUpdate(child);
In this case, I don't add the child to the parent's Children
collection, I just set the Parent
on the child object.
Is there any way to get NHibernate to persist this correctly so that when I grab the parent out of the database, it will have the child inside its Children
collection?
P.S. I realize that there's a potential issue here with the session cache and relying on NHibernate to perform some behind-the-scenes operations to make the data model correct, but I'm ignoring this issue for now.