加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法删除集合:[NHibernate.Exceptions.GenericADOExcepti

发布时间:2020-12-15 08:29:10 所属栏目:百科 来源:网络整理
导读:我有两个表,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" cascad
我有两个表,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>

当我尝试更新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.rnThe 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会为我们设置

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读