无法删除集合:[NHibernate.Exceptions.GenericADOException]

Ami*_*mar 8 c# nhibernate hibernate hbm

我有两个表,tableA和tableB.

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>
Run Code Online (Sandbox Code Playgroud)

当我尝试更新tableA中的记录时,它抛出异常,因为我在tableA实例中有子列表.

[NHibernate.Exceptions.GenericADOException] = {"无法删除集合:[MIHR.Entities.tableA.tableB#21] [SQL:UPDATE dbo.tableB SET tabAId = null WHERE tabAId = @ p0]"}

InnerException = {"无法将值NULL插入列'tabAId',表'SA_MIHR_DEV.dbo.tableB';列不允许空值.UPDATE失败.\ r \n语句已终止."}

Rad*_*ler 11

只有两种方法可以解决这个问题.

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>
Run Code Online (Sandbox Code Playgroud)

此设置(inverse ="true")将指示NHibernate直接从DB中删除项目.

虽然使用inverse="false"遗嘱总是导致:

  • UPDATE(带null)==从集合中删除的行为
  • DELETE item == cascade的行为

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);
Run Code Online (Sandbox Code Playgroud)

正如我们所看到的,我们明确指定了关系的两个方面.这必须从NHibernate逆映射中获益.这也是一种很好的做法,因为稍后,当我们从数据库加载数据时,我们期望NHibernate会为我们设置