Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate exception moving objects between collections

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
like image 955
Martin Avatar asked Mar 01 '26 18:03

Martin


1 Answers

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.

like image 109
Gluip Avatar answered Mar 03 '26 08:03

Gluip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!