tableA有列:tabAId,col2,col3(tabAId primaryKey和Identity列.)
tableB有列:tabAId,name(tabAId不为null)
我在tableA的hbm文件中创建了Bag,以维护关系.
<bag name="tableB" lazy="true" inverse="false" batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many class="tableB" /> </bag>
当我尝试更新tableA中的记录时,它抛出异常,因为我在tableA实例中有子列表.
[NHibernate.Exceptions.GenericADOException] = {“could not delete collection: [MIHR.Entities.tableA.tableB#21][sql: UPDATE dbo.tableB SET tabAId = null WHERE tabAId = @p0]”}
InnerException = {“Cannot insert the value NULL into column ‘tabAId’,table ‘SA_MIHR_DEV.dbo.tableB’;
column does not allow nulls. UPDATE fails.\r\nThe statement has been terminated.”}
解决方法
1)不要使用inverse =“false”
<bag name="tableB" lazy="true" inverse="true" // instead of false batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many class="tableB" /> </bag>
此设置(inverse =“true”)将指示NHibernate直接从DB中删除项目.
虽然使用inverse =“false”一般会导致:
> UPDATE(with null)==从集合中删除的行为
> DELETE item ==级联行为
2)使引用列可以为空
这意味着,我们可以让NHibernate进行UPDATE和DELETE.因为列现在可以为空.
这些只是两种解决方法.
我的偏好是:inverse =“true”
要使用inverse =“true”正常工作,我们总是必须在C#中指定关系的两面.这是Add(),INSERT操作必须的:
Parent parent = new Parent(); Child child = new Child { ... Parent = parent,}; // unless initialized in the Parent type,we can do it here parent.Children = parent.Children ?? new List<Child>(); parent.Children.Add(child); // now just parent could be saved // and NHibernate will do all the cascade as expected // and because of inverse mapping - the most effective way session.Save(parent);
正如我们所看到的,我们已明确指定了关系的两个方面.这必须从NHibernate逆映射中获益.这也是一种很好的做法,因为稍后,当我们从数据库加载数据时,我们期望NHibernate会为我们设置