实体对象的 XML 序列化

发布于 2024-10-17 23:19:10 字数 385 浏览 1 评论 0原文

我正在尝试将 EF 4.0 对象图序列化为 XML 以通过 WCF 服务传递。过去我曾使用 DTO/POCO 完成此操作(通常用于 JSON 序列化)。在这种情况下,因为我只进行 XML 序列化,所以似乎我应该能够直接序列化实体对象,但是,我遇到了这个难题:

  1. 如果我不分离实体,序列化会抛出一个错误,该错误表明对象上下文已被处置(因为它在那时已经被处置,所以这是预期的)。

  2. 如果我分离实体,导航属性中加载的所有相关对象都会被删除。

我的期望是,如果我枚举任何链接的实体,然后将该对象与上下文分离,我仍然可以将该关系用于序列化。

所以我的问题是,有没有办法直接序列化实体对象并保留任何加载的导航属性/集合?

谢谢...

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:

  1. 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).

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶视觉 2024-10-24 23:19:10

序列化对象时,序列化器将遍历整个对象图。

  • 如果您的对象已附加,它将强制加载每个延迟加载导航。因此,如果你的上下文被释放,你会得到一个异常。
  • 根据 msdn ,当导航属性中的某个项目被分离时,它不再出现在导航属性中。我认为分离对象并访问它的导航属性时是一样的。

我认为你应该在序列化之前从实体对象中创建 DTO/POCO。但是,您应该查看 automapper ,它将帮助您将对象从实体转换为 DTO 并返回。

When serializing an object, the serializer will walk the entire object graph.

  • If your object is attached, it will force-load every lazy-load navigations. Thus, if your context is disposed, you'll get an exception.
  • According to msdn, when an item in a navigation property is detached, it doesn't appear anymore in the navigation property. I think it is the same when detaching an object and accessing it's navigation property.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文