简体   繁体   English

使用Nhibernate删除对象时遇到问题

[英]Problems deleting object with nhibernate

I have some problems with deleting object. 我在删除对象时遇到一些问题。 I am getting the following error: 我收到以下错误:

[Test.Item#ab9a9869-b2c1-4262-8d33-9dd9010abd96][SQL: DELETE FROM InvoerItem WHERE DbId = ? [Test.Item#ab9a9869-b2c1-4262-8d33-9dd9010abd96] [SQL:从InvoerItem中删除,DbId =吗? AND Version = ?] AND版本=?]

The DELETE statement conflicted with the REFERENCE constraint "FK9100B9F130A0A610". DELETE语句与REFERENCE约束“ FK9100B9F130A0A610”冲突。 The conflict occurred in database "", table "dbo.InvoerItemToInvoerItem", column 'Listener_id'. 数据库“”的表“ dbo.InvoerItemToInvoerItem”的“ Listener_id”列中发生了冲突。

The situation is like this i have an object that has a collection of references to other objects of the same kind these are called listerners. 情况是这样的,我有一个对象,该对象具有对称为“侦听器”的同类对象的引用的集合。

The mapping for the object looks like this : 对象的映射如下所示:

public InvoerItemMap()
{
    HasManyToMany(x => x.Listeners)
        .ChildKeyColumn("Listener_id")
        .Cascade.None()
        .Access.CamelCaseField(Prefix.Underscore);
}

What is it that causes the exception when deleting an object that has a listeners connected to it? 是什么原因导致删除连接了侦听器的对象时发生异常? Do I have to inverse the relation ship of the listeners? 我必须逆转听众的关系吗?

No, inverse doesn't help. 不,逆没有帮助。

you need to specify what you want to do with the listeners. 您需要指定要对监听器执行的操作。 There are basically two options: 基本上有两种选择:

  • tell the user that there are listeners around and he can't delete this object 告诉用户周围有听众,他无法删除该对象
  • unregister the listeners by the software. 通过软件注销侦听器。

If you decide to unregister the listeners, then ... just implement it. 如果您决定取消注册监听器,则只需实施它即可。

InvoerItem itemToDelete = ...;
itemToDelete.Listeners.Clear();
session.Delete(itemToDelete);

It would be even better to let the entity manage the listeners: 让实体管理侦听器会更好:

itemToDelete.UnregisterListeners();

Edit : if you have references from the listeners to the invoerItems, you need to remove them as well: 编辑 :如果您有从侦听器到invoerItems的引用,则也需要删除它们:

public void UnregisterListeners()
{
    foreach(Listener listener in Listeners)
    {
        listener.Invoeritem = null;
    }
    Listeners.Clear();
}

By the way: in this case you should make the listeners inverse. 顺便说一句:在这种情况下,您应该使听众相反。 Don't forget to map it to the same foreign key. 不要忘记将其映射到相同的外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM