I basically have:
Public Class Job: MyBaseClass
{
public virtual string JobInformation {get;set;}
...
public virtual List<Item> JobItems {get;set;}
}
I was using a List and initializing it (JobItems = new List();) in the constructor. However, I was getting an Exception (Nhibernate.Collection.Generic.PersistentGenericBag)
I read this question and it said I should use IList instead.
So now I have
public class Job: MyBaseClass
{
public virtual string JobInformation {get;set;}
...
public virtual IList<Item> JobItems {get;set;}
}
public virtual v开发者_StackOverflowoid AddItem(Item item)
{
//snip validation
this.JobItems.Add(item);
}
However, it throws a NullReferenceException because JobItems isn't initialized yet. When does NHibernate initialize this collection? Or how can I solve this issue?
use a backing field and on return make sure it isn't null
public IList<Item> JobItems
{
get { return _jobItems ?? (_jobItems = new List<Item>()); }
set { _jobItems = value; }
}
You should initialize the collection if it hasn't been previously initialized.
private IList<Item> _jobItems;
public IList<Item> JobItems
{
get
{
return _jobItems ?? (_jobItems = new List<Item>());
}
private set
{
_jobItems = value;
}
}
精彩评论