I did something very similar to the code in the first post for a bag collection, but found my version didn't work...
Code:
private List<Category> _categories;
public List<Category> Categories
{
get { return _categories; }
set { _categories = value; }
}
public IList CategoriesNHibernate
{
get { return _categories; }
set
{
_categories.Clear();
foreach (Category category in value)
_categories.Add(category);
}
}
List<Category> satisfies
IList, so I can just return
_categories to NHibernate as is. (This turned out to be a crucial difference... I was returning my actual collection to NHibernate instead of a copy like the code in the first post did.)
The problem arose from the documented fact that NHibernate replaces CategoryNHibernate with its own collection class during a save or update, in this case
NHibernate.Collection.Bag. What I didn't know was this was actually a wrapper around the collection class I returned to NHibernate. So when I called
_categories.Clear(), I was actually clearing out
value (
NHibernate.Collection.Bag) as well, and deleting all my categories... (The foreach loop never found anything in
value to add.)
Note, this only happened in a save or update -- the retrieval of the object from the datastore works just fine, since
value (
NHibernate.Collection.Bag) in that case is not a wrapper but rather a new collection altogether.
If you want to do something similar, for bag at least, this modification solves the problem...
Code:
public IList CategoriesNHibernate
{
get { return _categories; }
set
{
List<Category> list = new List<Category>();
foreach (Category category in value)
list.Add(category);
_categories = list;
}
}
Or you can do what the code in the first post did and return a copy of the collection to NHibernate...
Code:
public IList CategoriesNHibernate
{
get { return new ArrayList(_categories); }
set
{
_categories.Clear();
foreach (Category category in value)
_categories.Add(category);
}
}