I have got two entities: Document and File connected in Many-To-Many relationship.
I want them to behave as follows:
- Document has many files.
 - Files can belong to many documents at the same time.
 - When I delete document, each file should be deleted as well, unless it belongs to another document.
 - When I delete some file from document, it should be deleted, unless it belongs to another document.
 
Entities:
public class Document
{
    public virtual int DocumentId { get; set; }
    public virtual ICollection<File> Files { get; set; }
}
public class File
{
    public virtual int FileId { get; set; }
    public virtual ICollection<Document> DocumentsAttachedIn { get; set; }
}
Mappings:
public DocumentMap()
{
    SelectBeforeUpdate();
    DynamicUpdate();
    Id(x => x.DocumentId).Column("DocumentId");
    HasManyToMany(x => x.Files)
        .AsSet()
        .Cascade.AllDeleteOrphan()
        .Table("DocumentFile")
        .ParentKeyColumn("DocumentId")
        .ChildKeyColumn("FileId");
}
public FilesMap()
{
    SelectBeforeUpdate();
    DynamicUpdate();
    Id(f => f.FileId).Column("FileId");
    HasManyToMany(f => f.DocumentsAttachedIn)
        .Inverse()
        .Table("DocumentFile")
        .ChildKeyColumn("DocumentId")
        .ParentKeyColumn("FileId");
}
I have saved two instances of Document, with the same file inside.
When I try to delete a file from Document.Files, or when I delete whole Document, I get following exception:
could not delete: [MyNameSpace.Files.Business.File#1][SQL: DELETE FROM File WHERE FileId = ?]
Inner Exception:
Cannot delete or update a parent row: a foreign key constraint fails (
my_base.documentfile, CONSTRAINTFKDB8FFE6221523AA6FOREIGN KEY (FileId) REFERENCESfile(FileId))
Indeed, I have such constraint and I want to keep it. The question is why NHibernate tries to delete it, when I explicitly told in mappings: Cascade.AllDeleteOrphan()
                        
The solution of these:
is: solve it yourself on the business layer. NHibernate cascade will not work here. It is there to do a cascade in full range (if turned on) or no (if turned off). Nothing between