Nhibernate not inserting parentid into child

百般思念 提交于 2019-12-12 03:23:09

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28233803/nhibernate-not-inserting-parentid-into-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!