LINQ to Entities - 优化查询
我在尝试优化/重构 LINQ to Entities 查询时遇到了一些问题。这是我目前所拥有的:
public List<Article> LastFive()
{
return _siteDB.Articles.OrderByDescending(a => a.LastModified).Take(5).ToList();
}
我想要做的是,我不想返回最近五篇文章的列表,而是只想获取最近五篇文章的标题和 ID。如果可能的话,我希望保持方法链完整(从风格的角度来看我喜欢它),但我不确定使用方法链为 Select()
放置什么。我也不确定将什么作为我的方法的返回值,因为我不会返回完整的 Article 实体,而只会返回其中选定的属性。 列表
?
I'm having a bit of a problem trying to refine/refactor a LINQ to Entities query. Here's what I currently have:
public List<Article> LastFive()
{
return _siteDB.Articles.OrderByDescending(a => a.LastModified).Take(5).ToList();
}
What I'd like to do is, instead of returning a list of the five most recent Articles, I'd like to simply get the Title and ID of the five most recent articles. I'd like to keep the method chaining intact, if possible (I like it from a style standpoint), but I'm not sure what to put for Select()
using method chaining. I'm also not sure what to put as my method's return value since I won't be returning full Article entities, but only selected properties from them. List<IQueryable>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好创建一个类型化类:
然后:
或者,由于您使用的是 C# 4.0,您可以选择要返回的属性:
要使用它:
It's better to create a typed class:
then:
or, since you are using C# 4.0, you can choose what properties to return:
To use it:
您可能应该返回实际类的列表,但该类仅包含您需要的属性。
这样你的查询就变成了:
You should probably return a List of an actual class, but a class containing only the properties that you need.
So that your query becomes: