3
votes

When moving an object from one collection to another and when cascade is set to all-delete-orphan, I get the following exception:

deleted object would be re-saved by cascade (remove deleted object from associations)

I thought that nhibernate would not delete an object when it is referenced in another collection when you use all-delete-orphan.

Can anyone confirm that, when you have objects like Folders which contain Folders or Files and you move a File from one Folder to another, you should not get this exception?

I made a sample project in vs2010 which demonstrates this behavior. Can anyone say if my mappings are correct or if there is a bug in nhibernate?

FileMapping.cs

public class FileMapping: ClassMap<File>
{
    public FileMapping()
    {
        Id(x => x.Id, "Id").GeneratedBy.Native("File_seq");
        Map(x => x.Name, "Name").Not.Nullable();
        References(x => x.Folder).Not.Nullable().Column("idFolder");
    }
}

FolderMapping.cs

public class FolderMapping: ClassMap<Folder>
{
    public FolderMapping()
    {
        Id(x => x.Id, "Id").GeneratedBy.Native("Folder_seq");
        Map(x => x.Name, "Name").Not.Nullable();
        HasMany(x => x.Folders).Inverse().Cascade.AllDeleteOrphan().KeyColumn("idParentFolder");
        HasMany(x => x.Files).Inverse().Cascade.AllDeleteOrphan().KeyColumn("idFolder");
        References(x => x.ParentFolder).Nullable().Column("idParentFolder");
    }
}

Sample project: http://www.mediafire.com/?orxcw63aziq54xo Instructions:

  1. make sure connectionstring in Project's Properties is correct
  2. run project
  3. click 1st button: connect to database
  4. click top right button to create tables and sample data (2 folder objects and 1 file)
  5. click button to move file object to other folder object
  6. click button to persist chances: you will get the DeletedObjectException
1
Do you get the exception regardless of whether you are moving a folder or a file, or does it only happen when attempting to move a folder to a different folder?Jay
@jay: I get the error when I move a file to another folder, but also remember seeing this exception when moving a folder to another folder. However, in my application this scenario is no longer supported, therefor that error doesn't show any longer. @vadim: Updated post with link and instructionsMartin

1 Answers

2
votes

NHibernate has a very local view on orphans. If an object is moved from folder A to folder B folder A considers it an orphan and therefore deletes it. Folder B wants to update the object and a conflict occurs.

It is called re-parenting and you read about it here http://fabiomaulo.blogspot.com/2009/09/nhibernate-tree-re-parenting.html

Basically this is a option to redefine what Orphan means in your collection so your objects don't get deleted.