返回匿名类型简单的方式(使MVC使用LINQ可能) [英] Simple way to return anonymous types (to make MVC using LINQ possible)

查看:122
本文介绍了返回匿名类型简单的方式(使MVC使用LINQ可能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时使用LINQ(特别是,LINQ到实体)来实现MVC。我会做到这一点的方法是让控制器生成(或某事物产生)的结果集使用LINQ,然后返回到视图中显示的数据。问题是,如果我做的:

I'd like to implement MVC while using LINQ (specifically, LINQ-to-entities). The way I would do this is have the Controller generate (or call something which generates) the result-set using LINQ, then return that to the View to display the data. The problem is, if I do:

return (from o in myTable select o);

全部的列从数据库中读取,即使我不想要的(潜在的几十个)。和 - 更重要的是 - 我的不能的做这样的事情:

All the columns are read from the database, even the ones (potentially dozens) I don't want. And - more importantly - I can't do something like this:

return (from o in myTable select new { o.column });

因为没有办法让匿名类型类型安全的!我知道肯定有3.5这样做的没有好的,干净的方式(的是不干净......),但对于4.0吗?有什么活动,甚至提出?没有像鸭打字换LINQ或类型安全的匿名返回值(在我看来,编译器当然应该是深谙此道),这似乎是几乎不可能干净控制器从视图中分离出来。

because there is no way to make anonymous types type-safe! I know for sure there is no nice, clean way of doing this in 3.5 (this is not clean...), but what about 4.0? Is there anything planned, or even proposed? Without something like duck-typing-for-LINQ, or type-safe anonymous return values (it seems to me the compiler should certainly be capable of that), it appears to be nearly impossible to cleanly separate the Controller from the View.

推荐答案

既然没有人甚至企图回答我的问题,我会回答它自己。

Since no one even attempted to answer my question, I will answer it myself..

原来,C#4.0支持鸭打字 - 他们称之为<一个href=\"http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx\"相对=nofollow>动态类型。然而,在使用动态类型返回匿名类型,我们失去强类型的好处:

It turns out, C# 4.0 supports duck-typing - they call it dynamic typing. However, in using dynamic types to return anonymous types, we lose the benefits of strong types:


  • 编译时类型检查

  • 性能

  • 智能感知

我已经开了一个功能要求有强类型的匿名返回类型<一个href=\"https://connect.microsoft.com/VisualStudio/feedback/details/542278/ability-to-return-strongly-typed-anonymous-classes#\"相对=nofollow>这里 - 如果你认为这将是一个有益的补充,以C#5,按照链接,让净的团队知道

I've opened a feature request to have strongly-typed anonymous return types here - if you think this would be a useful addition to C# 5, follow the link and let the .Net team know!

这篇关于返回匿名类型简单的方式(使MVC使用LINQ可能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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