Creating a NHibernate object and initializing a Set
-
06-07-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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.