views:

406

answers:

1

We are building a translation application which reads data from one database and translates it into a completely different format. We will be using NHibernate to read from the source database which is not yet available. We want to test the translation core logic by dummying up a source object, pass it through our translation core, and validating the output. Every time we attempt to add items to a one to many collection (declared as a PersistentGenericBag) we get NHibernate.LazyInitializationException: Initializing[Unavailable#]-failed to lazily initialize a collection, no session or session was closed. Has anyone tackled this?

private PersistentGenericBag<Child> _Children = null;
[NHibernate.Mapping.Attributes.Bag(1, Name = "Children", Table = "Children", Lazy = CollectionLazy.False, Cascade = "all")]
[NHibernate.Mapping.Attributes.Key(2)]
[NHibernate.Mapping.Attributes.Column(3, Name = "ParentId")]
[NHibernate.Mapping.Attributes.OneToMany(4, ClassType = typeof(Child))]
public virtual PersistentGenericBag<Child> Children
{
    get
    {
        if (_Children == null)
        {
            _Children = new PersistentGenericBag<Child>();
        }
        return _Children;
    }
    set { _Children = value; }
}


[TestMethod]
public void Xyz()
{
    Parent parent = new Parent ();
    parent.Children.Add(new Child()); //exception thrown here
    Assert.AreEqual(parent.Children.Count, 1);
}
+2  A: 

I agree with mausch, you should use try to stick to standard .Net collection elements like IList in your domain model instead of the NHibernate collections.

Once you do that you should be able to add and remove items from the collection without having any issues with NHibernate.

Andrew Hanson