Abhishek
Abhishek

Reputation: 11

Nhibernate not inserting parentid into child

I have a weird problem at hand. First have a look at my table schema.

A(ID) B(ID,AID) C(ID,AID) D(ID,CID)

The map files are as below:

MAP A
{
HasMany(x => x.B).Cascade.AllDeleteOrphan().Inverse().KeyColumn("AID");
HasMany(x => x.C).Cascade.AllDeleteOrphan().Inverse().KeyColumn("AID");
}

MAP B
{
References(x => x.A).Column("AID");
}

MAP C
{
References(x => x.A).Column("AID");
HasMany(x => x.D).Cascade.AllDeleteOrphan().Inverse().KeyColumn("BID");
}

MAP D
{
References(x => x.C).Column("CID");
}

While doing SaveORUpdate/Merge on A it doesn't insert AID into B and C. But it does insert CID into D. Any suggestions.

Upvotes: 1

Views: 667

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

If this happens, you for sure missed to assign both sides of relation. If this would be in place:

var parent = ...;
var child = ...;
parent.Children.Add(child);
child.Parent = parent;

All will work. Because the most supsected here is that your code is like:

var parent = ...;
var child = ...;
parent.Children.Add(child);
// child.Parent = parent; // this is missing

and that won't insert children. Why?

Because we used the .Inverse() mapping. This is a very powerful but fragile setting. It allows NHibernate to do some important optimizations, but that requires - PARENT must be set in child.

Check this nice article

Inverse = “true” example and explanation by mykong

Upvotes: 1

Related Questions