为什么NHibernate会在ISession.Refresh期间抛出“GenericADOException:无法初始化集合”异常?

时间:2011-08-02 14:50:33

标签: nhibernate nhibernate-mapping lazy-loading

ISession.Refresh()我一直在经历一种奇怪的行为(至少对我而言)。

我有一个带有延迟加载的子集合的实体,以及一个访问此集合的只读属性,它们都包含在二级缓存中。 我在长会话中使用ISession.Refresh()来在将事务提交到DB后获取最新数据,并得到以下错误:

NHibernate.Exceptions.GenericADOException : could not initialize a collection: [Test.NUnit.DBTest.TestModel.ParentTestEntity.Children#d4251363-cf88-4684-b65a-9f330107afcf][SQL: SELECT children0_.ParentTestEntity_id as ParentTe4_1_, children0_.Id as Id1_, children0_.Id as Id42_0_, children0_.RowVersion as RowVersion42_0_, children0_.Parent_id as Parent3_42_0_ FROM "ChildTestEntity" children0_ WHERE children0_.ParentTestEntity_id=?]
  ----> System.NullReferenceException : Object reference not set to an instance of an object.
    at NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type)
    at NHibernate.Loader.Collection.CollectionLoader.Initialize(Object id, ISessionImplementor session)
    at NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize(Object key, ISessionImplementor session)
    at NHibernate.Event.Default.DefaultInitializeCollectionEventListener.OnInitializeCollection(InitializeCollectionEvent event)
    at NHibernate.Impl.SessionImpl.InitializeCollection(IPersistentCollection collection, Boolean writing)
    at NHibernate.Collection.AbstractPersistentCollection.Initialize(Boolean writing)
    at NHibernate.Collection.AbstractPersistentCollection.ReadSize()
    at NHibernate.Collection.PersistentBag.get_Count()
    DBTest\TestModel\EntiteTestCacheCollectionsParent.cs(25,0): at Test.NUnit.DBTest.TestModel.ParentTestEntity.get_Count()
    at (Object , GetterCallback )
    at NHibernate.Bytecode.Lightweight.AccessOptimizer.GetPropertyValues(Object target)
    at NHibernate.Tuple.Entity.PocoEntityTuplizer.GetPropertyValuesWithOptimizer(Object entity)
    at NHibernate.Tuple.Entity.PocoEntityTuplizer.GetPropertyValues(Object entity)
    at NHibernate.Persister.Entity.AbstractEntityPersister.GetPropertyValues(Object obj, EntityMode entityMode)
    at NHibernate.Event.Default.AbstractVisitor.Process(Object obj, IEntityPersister persister)
    at NHibernate.Event.Default.DefaultRefreshEventListener.OnRefresh(RefreshEvent event, IDictionary refreshedAlready)
    at NHibernate.Event.Default.DefaultRefreshEventListener.OnRefresh(RefreshEvent event)
    at NHibernate.Impl.SessionImpl.FireRefresh(RefreshEvent refreshEvent)
    at NHibernate.Impl.SessionImpl.Refresh(Object obj)
    DBTest\NHibernateBehaviorTests.cs(610,0): at Test.NUnit.DBTest.NHibernateBehaviorTests.Test()
    --NullReferenceException
    at NHibernate.Engine.Loading.CollectionLoadContext.AddCollectionToCache(LoadingCollectionEntry lce, ICollectionPersister persister)
    at NHibernate.Engine.Loading.CollectionLoadContext.EndLoadingCollection(LoadingCollectionEntry lce, ICollectionPersister persister)
    at NHibernate.Engine.Loading.CollectionLoadContext.EndLoadingCollections(ICollectionPersister persister, IList`1 matchedCollectionEntries)
    at NHibernate.Engine.Loading.CollectionLoadContext.EndLoadingCollections(ICollectionPersister persister)
    at NHibernate.Loader.Loader.EndCollectionLoad(Object resultSetId, ISessionImplementor session, ICollectionPersister collectionPersister)
    at NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly)
    at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
    at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
    at NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type)

这是一个用简化模型显示问题的单元测试:

    [Test]
    public void Test()
    {
        ISession session1 = NHibernateHelper.SessionFactory.OpenSession();
        ISession session2 = NHibernateHelper.SessionFactory.OpenSession();

        // Create a new entity tree and persist it
        ParentTestEntity parentSession1 = new ParentTestEntity();
        parentSession1.AddChild(new ChildTestEntity());
        session1.Save(parentSession1);
        session1.Flush();

        // Load the saved object into another session
        ParentTestEntity parentSession2 = session2.Get<ParentTestEntity>(parentSession1.Id);
        session2.Refresh(parentSession2); // Throws here
    }

以下是涉及的实体:

public class ParentTestEntity
{
    public virtual Guid Id { get; private set; }
    public virtual long RowVersion { get; private set; }

    public virtual IList<ChildTestEntity> Children { get; protected set; }

    public ParentTestEntity()
    {
        this.Children = new List<ChildTestEntity>();
    }

    public virtual int Count
    {
        get
        {
            return Children.Count;
        }

        set { }
    }

    public virtual void AddChild(ChildTestEntity child)
    {
        if (this.Children == null)
        {
            this.Children = new List<ChildTestEntity>();
        }

        this.Children.Add(child);
        child.Parent = this;
    }
}

public class ChildTestEntity
{
    public virtual Guid Id { get; private set; }
    public virtual long RowVersion { get; private set; }

    public virtual ParentTestEntity Parent { get; set; }
}

他们的映射:

public class ParentTestEntityMap : ClassMap<ParentTestEntity>
{
    public ParentTestEntityMap()
    {
        Cache.ReadWrite();

        Id(x => x.Id)
            .GeneratedBy.GuidComb();

        Version(x => x.RowVersion);

        HasMany(x => x.Children)
            .Inverse()
            .Cascade.All()
            .Cache.ReadWrite();

        Map(x => x.Count);
    }
}

public class ChildTestEntityMap : ClassMap<ChildTestEntity>
{
    public ChildTestEntityMap()
    {
        Cache.ReadWrite();

        Id(x => x.Id)
            .GeneratedBy.GuidComb(); 

        Version(x => x.RowVersion);

        References(x => x.Parent)
            .Not.Nullable();
    }
}

在我的测试中,我发现了:

  • 删除Count属性
  • 的映射
  • 删除Cache.ReadWrite()映射,
  • Refresh之前枚举集合,

足以让Refresh正常工作。

任何人都知道如何让Refresh工作?

注意:

  • 我可以在NHibernate 2.1.2和3.1.0中重现这种行为,
  • 我知道Count中的空setter是丑陋的,只是为了反映实体模型中实体的映射。

2 个答案:

答案 0 :(得分:1)

使用Load()取代Get()来解决问题。

这不是一般解决方案,因为Load()的语义略有不同,如果相应的行不存在则会抛出。

这是我们架构中可接受的约束,因为我们知道加载的entites存在于数据库中。

然而,仍然欢迎使用Get()的任何解决方案。

答案 1 :(得分:0)

请参阅my answer for a similar question, "Cannot assign property value in entity's constructor"。我不会在这里详细介绍所有细节,因为你可以在那里阅读。

简短的回答是,您正在构建器中访问虚拟属性,这是禁忌。以下更改应解决问题。替换这些线......

public virtual IList<ChildTestEntity> Children { get; protected set; }

public ParentTestEntity()
{
    this.Children = new List<ChildTestEntity>();
}

......用以下几行:

private IList<ChildTestEntity> _children;

public virtual IList<ChildTestEntity> Children
{
    get { return _children; }
    protected set { _children = value; }
}

public ParentTestEntity()
{
    _children = new List<ChildTestEntity>();
}

FxCop和ReSharper是两种可以自动识别此问题的不同工具。