NHibernate用WCF序列化惰性加载实体

本文关键字:加载 实体 序列化 WCF NHibernate | 更新日期: 2023-09-27 17:49:41

我试图通过使用WCF的电线发送NH实体。我有一个惰性加载对象的复杂图形。我尝试实现一个自定义的datacontractproxy,以便在序列化时强制初始化。下面是代码:

public class HibernateDataContractSurrogate : IDataContractSurrogate
{
    public HibernateDataContractSurrogate()
    {
    }
    public Type GetDataContractType(Type type)
    {
        // Serialize proxies as the base type
        if (typeof(INHibernateProxy).IsAssignableFrom(type))
        {
            type = type.GetType().BaseType;
        }
        // Serialize persistent collections as the collection interface type
        if (typeof(IPersistentCollection).IsAssignableFrom(type))
        {
            foreach (Type collInterface in type.GetInterfaces())
            {
                if (collInterface.IsGenericType)
                {
                    type = collInterface;
                    break;
                }
                else if (!collInterface.Equals(typeof(IPersistentCollection)))
                {
                    type = collInterface;
                }
            }
        }
        return type;
    }
    public object GetObjectToSerialize(object obj, Type targetType)
    {
        if (obj is INHibernateProxy)
        {
            obj = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation();
        }
        // Serialize persistent collections as the collection interface type
        if (obj is IPersistentCollection)
        {
            IPersistentCollection persistentCollection = (IPersistentCollection)obj;
            persistentCollection.ForceInitialization();
            obj = persistentCollection.Entries(null); // This returns the "wrapped" collection
        }
        return obj;
    }
    public object GetDeserializedObject(object obj, Type targetType)
    {
        return obj;
    }
    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
    {
        return null;
    }
    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        return null;
    }
    public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
    {
    }
    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        return null;
    }
    public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
    {
        return typeDeclaration;
    }
}

然而,我一直得到异常:

NHibernate.Exceptions.GenericADOException: could not initialize a collection [SQL trace] ---> System.ObjectDisposedException: Session is closed!

查看堆栈跟踪,似乎这一行persistentCollection.ForceInitialization();正在抛出异常。

我能做什么?

PS:我想使用DTO而不是序列化复杂的NH实体,但这在这里是不可能的。

NHibernate用WCF序列化惰性加载实体

在关闭加载集合的NHibernate.ISession对象后,不能惰性加载集合。你唯一的选择是:

  1. 保持ISession打开,直到数据序列化完成。
  2. 关闭延迟加载
  3. 确保在关闭会话之前获取所有延迟加载的集合。

查看这里的答案:向客户端发送Hibernate代理类有哪些问题