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

标签 c# hibernate nhibernate hbm

我有两个表,tableA 和 tableB。

tableA 有列:tabAId、col2、col3 (tabAId primaryKey 和 Identity 列。)

tableB 有列:tabAId,名称(tabAId 不为空)

我在表A的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 直接从数据库中删除一个项目

虽然使用 inverse="false" 通常会导致:

  • UPDATE (with null) == 从集合中移除的行为
  • 删除项目 == 级联行为

2) 使引用列可以为空

这意味着,我们可以让 NHibernate 去执行更新和删除。因为列现在可以为空。

这里只有两种解决方法。

我的偏好是: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 会为我们注意设置

关于c# - 无法删除集合 : [NHibernate. Exceptions.GenericADOException],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045648/

相关文章:

c# - NHibernate 无需代理即可获取对象

c# - 获取到两个向量的距离为 x 的 Vector2

java - "java.lang.AbstractMethodError: org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager" hibernate

mysql - hibernate ,mysql

java - 如何使 Hibernate 在 Oracle 上为 JPA GenerationType.AUTO 使用 SequenceHiLoGenerator?

.net - 如何添加 NHibernate 配置文件以使用 NHibernate.Search?

nhibernate - 使用 Fluent NHibernate 删除一对一关系中的实体时出现级联问题

c# - 识别数组中基类的实现

c# - 为 IDBCommand 与 SqlCommand.ExecuteNonQueryAsync 实现 Async ExecuteNonQuery()

c# - 如何检测 *IIS 用户* 是否已在远程桌面连接中运行该网站