如何在不修改类的情况下从序列化中排除属性?
我有一个 WCF REST Web 服务,它返回由 Entity Framework 4 生成的 POCO 实体。根据 HTTP 请求的 ContentType,该服务可以返回 XML 或 JSON。这正是我所需要的。但是,某些实体具有太多属性,我不想返回所有这些数据。 我的方法现在如下所示:
public IEnumerable<Task> GetTasks()
{
Tasks myTasks = ...
return myTasks;
}
我不想查看 Task 类的所有属性,因此我想返回一个 XElement 对象。这使我能够完全控制 XML,而且它的工作方式非常神奇。但是,我失去了 WCF 的 JSON 功能部分。
public XElement GetTasks()
{
Tasks myTasks = ...
return new XElement("Tasks", myTasks.Select(a => ToXml(a));
}
如何排除属性(不修改类,我可能在另一个方法中需要这些属性)而不丢失 WCF 处理的 XML / JSON 响应?
I have a WCF REST Web Service which returns POCO entities generated by Entity Framework 4. Based on the ContentType of the HTTP request, the service can return XML or JSON. This is exactly what I need. However, some of the entities have too many properties and I don’t want to return all this data.
Here is how my method looks right now:
public IEnumerable<Task> GetTasks()
{
Tasks myTasks = ...
return myTasks;
}
I don’t want to see all the properties of the Task class, so I though of returning an XElement object instead. This gives me full control on the XML and it works like a charm. However, I am losing the JSON functionality part of WCF.
public XElement GetTasks()
{
Tasks myTasks = ...
return new XElement("Tasks", myTasks.Select(a => ToXml(a));
}
How do I exclude properties (without modifying the class, I might need those properties in another method) without losing the XML / JSON response handled by WCF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意 DTO,但我不确定 AutoMapper 是否是适合这种情况的工具。基本上你想返回有限的数据集。在 WCF 的世界中,这意味着您需要另一个类 = DTO。 AutoMapper 是一个很好的工具,可以从一个类映射到另一个类,但这意味着您必须从数据库加载整个对象。但是,如果在请求的操作中不需要它们,为什么要加载整个对象及其所有属性呢?请改用 Linq-to-entities 投影。它需要手动进行映射,但这是更有效的方法。
I agree with DTO but I'm not sure if AutoMapper is the tool for this scenario. Basically you want to return limited set of data. In the world of WCF it means you need another class = DTO. AutoMapper is a great tool to map from one class to other class but it means that you must load whole object from database. But why to load the whole object with all its properties if you don't need them in the requested operation? Use Linq-to-entities projection instead. It requires to do mapping manually but it is more effective approach.
您可以使用 DTO 对象,然后在模型和该对象之间进行映射。 AutoMapper 是一个很棒的框架:
可以随意在此对象中包含您需要的任何属性。
You could use a DTO object and then map between the model and this object. AutoMapper is a great framework for this:
Feel free to include whatever properties you need in this object.