开发者

Using IList in Nhibernate, does not get initialized

开发者 https://www.devze.com 2023-01-27 09:17 出处:网络
I basically have: Public Class Job: MyBaseClass { public virtual string JobInformation {get;set;} ... public virtual List<Item> JobItems {get;set;}

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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消