我正在尝试使用WCF通过线路发送NH实体。我有一个懒惰加载对象的复杂图表.. 我尝试在序列化时实现自定义DataContractSurrogate以强制初始化。 这是代码:
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 :(得分:1)
在关闭加载它的NHibernate.ISession
对象后,您无法延迟加载集合。您拥有的唯一选择是:
ISession
打开,直到您序列化数据。答案 1 :(得分:1)