2011-04-08 57 views
2

我想通過使用WCF的電線發送NH實體。我有一個延遲加載的對象的複雜圖形.. 我試圖實現一個自定義DataContractSurrogate強制初始化時序列化。 下面是代碼:NHibernate序列化與WCF的延遲加載實體

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實體,但在這裏是不可能的。

+0

我能問你爲什麼要使用延遲加載? – Aliostad 2011-04-08 11:54:43

回答

1

在關閉加載對象的NHibernate.ISession對象後,您無法延遲加載集合。您唯一的選擇是:

  1. 保持ISession開放,直到您序列化數據。
  2. 關閉延遲加載。
  3. 確保您在關閉會話之前獲取所有延遲加載的集合。