延迟加载返回相同的记录

时间:2010-10-29 14:42:35

标签: c# nhibernate lazy-loading

我有实体:

public class Document : PersistentObjectBase
{
    public virtual long? FolderId
    {
        get;
        set;
    }
}

<id name="Id" column="ID">
  <generator class="identity" />
</id>

<version column="VERSION" name="Version" type="Int64" unsaved-value="undefined" />

<property name="FolderId" column="FOLDER" />

public class DocumentFolder : PersistentObjectBase
{
    public virtual long? ParentFolderId
    {
        get;
        set;
    }

    #region [Lazy subfolders]

    protected virtual IList<DocumentFolder> NSubFolders
    {
        get;
        set;
    }

    public virtual IList<DocumentFolder> SubFolders
    {
        get
        {
            return GetObjectWithInitializationCheck(NSubFolders);
        }
        set
        {
            NSubFolders = value;
        }
    }

    #endregion

    #region [Lazy Documents]

    protected virtual IList<Document> NDocuments
    {
        get;
        set;
    }

    public virtual IList<Document> Documents
    {
        get
        {
            return GetObjectWithInitializationCheck(NDocuments);
        }
        set
        {
            NDocuments = value;
        }
    }

    #endregion
}

其中:

    protected static T GetObjectWithInitializationCheck<T>(T propertyValue) where T : class
    {
        if (ObjectInitialized(propertyValue))
        {
            return propertyValue;
        }
        return null;
    }

<id name="Id" column="ID">
  <generator class="identity" />
</id>

<version column="VERSION" name="Version" type="Int64" unsaved-value="undefined" />

<property name="ParentFolderId" column="PARENT_FOLDER_ID" />

<bag name="NSubFolders" lazy="true" cascade="delete">
  <key column="PARENT_FOLDER_ID" />
  <one-to-many class="DocumentFolder" />
</bag>

<bag name="NDocuments" lazy="true">
  <key column="FOLDER" />
  <one-to-many class="Document" />
</bag>

在建立标准时,我这样做:

criteria.SetResultTransformer(new DistinctRootEntityResultTransformer());
criteria.CreateCriteria("NSubFolders", "subFolders", JoinType.LeftOuterJoin);
criteria.CreateCriteria("NDocuments", "documents", JoinType.LeftOuterJoin);

该方法返回包含子文件夹和文档的文件夹,但可以在列表中多次查找文件夹。 例如,我只有30个文件夹,但我得到大约180个文件夹,而不是1个文件夹。 抱歉我的英语不好......

1 个答案:

答案 0 :(得分:1)

最喜欢你的JoinType。使用另一个Type(例如Select),LeftOuterJoin为每个1:n关系返回n行。