views:

568

answers:

2

Hi,

I have a Table called Product and I have the Table StorageHistory.

Now, Product contains a reference to StorageHistory in it's mappings

<set name="StorageHistories" lazy="false">
  <key column="ProductId" />
  <one-to-many class="StorageHistory" />
</set>

And it works, when I retrieve an object from the ORM I get an empty ISet.

What gives me a headache is how to construct the object in the first place. When I do the following:

var product = new Product();
session.Save(product);

the product.StorageHistories property is NULL and I get a NullReferenceException. So, how do I add items to that collection, or should I go the way to add the StorageHistory items themselves to the DB?

+5  A: 

I always do the following in the ctor of the parent object:

histories = new HashedSet();

This covers the Save() use case. The Load()/Get() etc usecase is covered by NHibernate as you stated.

Quibblesome
Hmm.. this leads to the problem that I'll be calling a virtual Member from the constructor. Which may cause problems: http://blogs.msdn.com/brada/archive/2004/08/12/213951.aspx
Tigraine
Leaves me with the problem that I need to persistent *StorageHistory* before I actually save *Product*, what leads to the problem that *StorageHistory* has a Fk to *Product* that can't be null. So I'll have to persist Product, persist Storagehistory, update Product to insert a Product w. a History.
Tigraine
switch the association then. So you can do: history.Product = product. session.Save(history); session.Refresh(product);
Quibblesome
Actually Tigraine that pesistent StorageHistory before saving product depends on how your cascading is set on your Product. I've been able to save an object with it's associations just by calling save on the object.
Min
A: 

Why not?

private ISet _StorageHistories;
public virtual ISet StorageHistories {
     protected set { _StorageHistories = value;}
     get { if (_StorageHistories == null) _StorageHistories = new HashSet();
           return _StorageHistories;
     }
}

Of course if you go through the trouble of having a private anyway you might as well put it in the constructor.

Min

related questions