I have a class that conatins a collection that is mapped to a many-to-many database relationship using Fluent Nhibernate. The mapping is as below -
Table("Book");
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.NumberOfPages);
HasManyToMany(x => x.Authors)
.Cascade.AllDeleteOrphan()
.Table("BookAuthor")
.ParentKeyColumn("BookId")
.ChildKeyColumn("AuthorId");
I then get an instance of this class and add an item to the authors collection using the code below -
var book = session.CreateCriteria(typeof(Book)).UniqueResult<Book>();
Author author = new Author {Name="Phil Moran",Age=51};
book.Authors.Add(author);
session.SaveOrUpdate(book);
The database is updated succesfully but Nhibernate updates the BookAuthor table by firstly deleting all the records within it linked to the updated book, then repopulating all the data plus the extra record required for the new author. Why is Nhibernate doing this? I would expect it to simply add a single record containing the book and author details to the many-to-many table (BookAuthor) and not perform any of the delete actions. Can I change this behaviour via my mappings?