views:

37

answers:

1

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?

+2  A: 

That happens when the collection is mapped as a bag (I guess that's the default in FluentNH).

Use a set, list or idbag instead.

Diego Mijelshon
Thanks Diego, I was defining my collection as an IList which I think maps the collection to a bag by default. I changed my collection defintion to this - private ISet<Author> _authors = new HashedSet<Author>();public virtual ISet<Author> Authors....And everything worked as expected.
ipr101

related questions