Backing field for collection is null when using Li

2019-07-18 17:54发布

问题:

I am having a problem when I try switching from the Castle ProxyFactoryFactory to the LinFu ProxyFactoryFactory in NHibernate.

I have an entity like this:

public class Foo
{
    private ISet<Bar> _bars = new HashedSet<Bar>();

    public virtual void AddBar(Bar bar)
    {
       if (!_bars.Contains(bar)
            _bars.Add(bar);

       bar.Foo = this;
    }
}

This is mapped with Fluent NHibernate like this:

public class FooDbMap : ClassMap<Foo>
{
     public FooDbMap()
     {
          HasMany(x => x.Bars)
              .Access.CamelCaseField(Prefix.Underscore)
              .LazyLoad()
              .KeyColumn("FooId")
              .AsSet()
              .Cache.ReadWrite();
     }
}

The relationship is bi-directional and is mapped as such on the Bar side too.

The problem occurs when I call the AddBar method. The _bars collection is null, and a NullReferenceException is thrown.

The problem goes away if I switch back to the Castle ProxyFactoryFactory.

The error doesn't occur with all mapped collections, just this one instance.

The problem still occurs even if I change _bars to readonly! So someone is managing to set a readonly field back to null, even after the field has been assigned.

Any ideas?