在 C# 中返回匿名类型的集合
我有一个 VS2010 解决方案,由两个项目组成 - 一个“数据”项目和一个使用该数据项目的 Web 服务项目。为了防止暴露数据库模式,我选择将匿名 (var) 对象返回给 Web 服务的使用者。我的问题是,我返回的一些东西将被收藏。因此,我不想使用此代码返回单个匿名对象:
var item = from w in db.Widgets
where w.widget_id == 1
select new {
name = w.name,
address = w.address
};
我想使用与此类似的东西来返回集合。
IQueryable<var> item = (from w in db.Widgets
where w.widget_id == 1
select new {
name = w.name,
address = w.address
}).IQueryable;
我意识到这不是执行此操作的确切方法......只需要知道它实际上是如何完成的。
谢谢!
I have a VS2010 solution consisting of two projects - a "data" project and a webservice project that consumes the data project. In order to protect from exposing the schema of the database I've opted to return anonymous (var) objects to the consumer of the webservice. My question is, some of what I return will be in collections. So instead of using this code to return a single anonymous object:
var item = from w in db.Widgets
where w.widget_id == 1
select new {
name = w.name,
address = w.address
};
I would want to use something similar to this to return a collection.
IQueryable<var> item = (from w in db.Widgets
where w.widget_id == 1
select new {
name = w.name,
address = w.address
}).IQueryable;
I realize this is not the exact way to do this ... just need to know how it would really be done.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
匿名类型本身不能在其声明函数之外公开,因此在声明函数之外公开匿名类型实例的唯一方法是将其作为
对象
。如果您需要执行此操作,则必须在更高范围内声明具有所需属性的类型,然后在查询中将其水化而不是匿名类型。Anonymous types themselves cannot be exposed outside of their declaring function, so the only way to expose an instance of an anonymous type outside of the declaring function is as an
object
. If you need to do this, you'll have to declare a type at a higher scope with the properties that you need, then hydrate it within your query rather than the anonymous type.我不会返回匿名类型,而是返回一个强类型层。它仍然可以以您想要的任何方式从数据库中填充,并且您将与服务的消费者签订强有力的合同。消费者甚至不知道有一个数据库,它也可能是 xml。
Instead of returning anonymous types, I'd have a strong typed layer that is returned. It can still be filled from the database in whichever way you want and you'd have a strong contract for the consumer of the service. The consumer won't even know there is a database, it could just as well be xml.
理论上,你可以这样做:
但是,我不明白你为什么要这样做——调用者显然无法使用你的匿名类型,除非通过反射或其他黑客的东西。为什么不干脆返回一个大家都可以正常使用的普通类呢?
You could, in theory, do this:
However, I don’t understand why you want to do this — the caller will obviously not be able to make any use of your anonymous type, except via Reflection or other hacky stuff. Why not simply return a normal class that everyone can use normally?