实体对象的 XML 序列化
我正在尝试将 EF 4.0 对象图序列化为 XML 以通过 WCF 服务传递。过去我曾使用 DTO/POCO 完成此操作(通常用于 JSON 序列化)。在这种情况下,因为我只进行 XML 序列化,所以似乎我应该能够直接序列化实体对象,但是,我遇到了这个难题:
如果我不分离实体,序列化会抛出一个错误,该错误表明对象上下文已被处置(因为它在那时已经被处置,所以这是预期的)。
如果我分离实体,导航属性中加载的所有相关对象都会被删除。
我的期望是,如果我枚举任何链接的实体,然后将该对象与上下文分离,我仍然可以将该关系用于序列化。
所以我的问题是,有没有办法直接序列化实体对象并保留任何加载的导航属性/集合?
谢谢...
I am trying to serialize and EF 4.0 object graph to XML to pass via a WCF service. In the past I have done this with DTO's/POCO's (usually for JSON serialization). In this case since I am only doing XML serialization it seemed that I should just be able to serialize the entity objects directly however, I am running into this conundrum:
If I do not detach the entity, serialization throws an error that the object context has been disposed (because it has at that point so this is expected).
If I detach the entity, any related objects loaded in the navigation properties are dropped.
My expectation was that if I enumerated any linked entities, then detached the object from the context I would still have that relationship available for serialization.
So my question, is there anyway to directly serialize an entity object and retain any loaded navigation properties/collections?
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
序列化对象时,序列化器将遍历整个对象图。
我认为你应该在序列化之前从实体对象中创建 DTO/POCO。但是,您应该查看 automapper ,它将帮助您将对象从实体转换为 DTO 并返回。
When serializing an object, the serializer will walk the entire object graph.
I think you should make DTO/POCO's from you entity object before serializing. However, you should have a look at automapper which will help you converting your object from entity to DTO and back.