oriches wrote:
Thanks for the response, I know that nHibernate can access the private variable to 'set' the property, but this would miss some of the business logic I wish to apply to each member of the collection when it is added.
Cheers
Ollie
I think the idea is that NHibernate assumes that when it's hydrating an object, that it's just bring back into memory what was once in memory some time ago and then persisted. So, if you have the following lifecycle..
1.) New object is created.
2.) Entity is added to collection via the Add method, which includes validation. Let's say that all checks in the Add method are OK, thus the Bar object is successfully added to the Children collection.
3.) Save() is called, persisting the entity to the DB.
4.) You close your program and make yourself a sandwich.
5.) You open your program, calling Load<Foo>(id)
Since the DB should only have entities that already did pass the validation in Add, it's redundant to check them again in AddRange. If the Bar entity you passed duing your pre-lunch session didn't pass the validation in Add, it would never have been persisted.
As jta explained, by not making your set publicly available, and instead forcing the user of the class to use your methods with the validation in them, you should be able to safely say that every entity in the collection passed the validation.
Now, there may be exceptions, two I can think of are...
1.) Your DB is being shared with another program that doesn't use your validation.
2.) You are creating a new version of your program that has tighter validation than a previous version, and entities in the DB might have been valid in a previous version, but no longer valid in the new version.
In either case, you may want to go with more of a passive validation scheme (using an IsValid() method on foo, for example). In the second case, you might also want to think of alter scripts for your database to bring entities that would become invalid into a valid state.
Hope that helps.