1

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 void 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?

Community
  • 1
  • 1
Nathan Koop
  • 24,803
  • 25
  • 90
  • 125

2 Answers2

3

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; }
}
Handcraftsman
  • 6,863
  • 2
  • 40
  • 33
  • Is there any specific reason why this does not work if I initialize this collection in constructor like this `JobItems = new List()` – Gaurav Arora Jun 26 '14 at 16:48
1

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;
    }
}
Lester
  • 4,243
  • 2
  • 27
  • 31