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:
- make sure connectionstring in Project's Properties is correct
- run project
- click 1st button: connect to database
- click top right button to create tables and sample data (2 folder objects and 1 file)
- click button to move file object to other folder object
- click button to persist chances: you will get the DeletedObjectException
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.