could not delete collection : [NHibernate.Exceptions.GenericADOException]

帅比萌擦擦* 提交于 2019-12-22 04:28:16

问题


I have Two Table , tableA and tableB.

tableA have column : tabAId, col2, col3 (tabAId primaryKey and Identity column.)

tableB have column : tabAId, name (tabAId is not null)

I have create Bag in hbm file of tableA, to maintain relation ship.

<bag name="tableB" lazy="true" inverse="false"
                    batch-size="25" cascade="all-delete-orphan">
  <key column="tabAId" />
  <one-to-many class="tableB" />
</bag>

When I try to update record in tableA it throw exception, where as I have list of child in tableA instance.

[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:


There are only two ways how to solve this.

1) do not use 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>

This setting (inverse="true") will instruct NHibernate to directly delete an item from DB.

While using inverse="false" will in general always lead to:

  • UPDATE (with null) == act of removing from collection
  • DELETE item == act of cascade

2) make the reference column nullable

That means, that we can leave NHibernate to do UPDATE and DELETE. Because column is now nullable.

These are only two ways how to solve it here.

My preference would be: inverse="true"

To work properly with inverse="true" we always have to assign both sides of relation in C#. This is a must for Add(), INSERT operation:

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);

As we can see, we have assigned - explicitly - both sides of relationship. This is must to profit from NHibernate inverse mapping. And it is also good practice, because later, when we load data from DB we expect, that NHibernate will take care about setting that for us



来源:https://stackoverflow.com/questions/30045648/could-not-delete-collection-nhibernate-exceptions-genericadoexception

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