单个实体引用的WCF序列化和NHibernate代理 [英] WCF Serialization and NHibernate Proxy for a Single Entity Reference

查看:62
本文介绍了单个实体引用的WCF序列化和NHibernate代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个NHibernate实体"School",其"Manager"属性引用了一个类型为"Person"的实体.

Suppose there is NHibernate entity "School" with a "Manager" property which references a single entity of type "Person".

要成为"WCF就绪",Person用DataContractAtrribute装饰. School.Manager的Fluent NH映射为References(s => s.Manager). 当WCF将类型为学校"的实体发送到客户端时,我收到以下消息的异常:

To be "WCF ready", Person is decorated with DataContractAtrribute. The Fluent NH mapping for School.Manager is References(s => s.Manager). When an entity of type "School" is sent to the client by WCF I get an exception with the following message:

类型'Castle.Proxies.PersonProxy'不能被ISerializable并具有DataContractAttribute属性"

"Type 'Castle.Proxies.PersonProxy' cannot be ISerializable and have DataContractAttribute attribute"

现在,这仅在引用单个实体时发生(而不是通过集合). 我的解决方法是通过在References子句中添加.Not.LazyLoad()来禁用代理.

Now, this only happens when referencing a single entity (and not through a collection). My workaround is to disable the proxy by adding .Not.LazyLoad() to the References clause.

有人遇到这个问题或有任何解决办法的想法吗?

Did anyone encounter this problem or have any idea how to resolve it?

谢谢, 逃跑

推荐答案

当您选择不急于加载时,NHibernate将创建动态代理(以便可以在未来).这是标准行为.

When you chose not to load referenced entities eagerly, NHibernate will create dynamic proxies (so that object can be initialized at some point in future). That's standard behavior.

现在,对于对象列表,NHibernate将使用其代理集合之一(例如,PersistentGenericBag).由于集合类型是已知的,因此可以序列化.当它代替您的实体类时会发生什么?它将根据您的类型生成动态代理,该代理将无法序列化(由于它具有面向运行时/动态的特性).

Now, for list of objects, NHibernate will use one of its proxy collections (for example, PersistentGenericBag). Since the collection type is known, it can be serialized. What happens when it approaches your entity class instead? It will generate dynamic proxy basing on your type, which won't be serializable (thanks to it runtime-oriented/dynamic nature).

这是内置的机制,我认为您对此无能为力.但是,您有两种解决此问题的方法:

This is built in mechanism and I don't think you can do much about it. Yet, you have two solutions to this problem:

  • 像现在一样使用Not.LazyLoad()强制创建实例
  • 或者,您可以在通过Web服务发送之前将Manager设置为null.无论如何,您将不会在客户端使用任何代理(因为会话将长期消失).
  • using Not.LazyLoad() like you're doing now, to force instance creation
  • alternatively, you can set Manager to null before sending through web service. You won't have any use of proxy on client side (since session will be long gone) anyways.

这篇关于单个实体引用的WCF序列化和NHibernate代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆