通过linq返回Non IQueryable值

时间:2013-04-30 11:59:24

标签: entity-framework linq iqueryable

在特定情况下,我正在编写此方法以按类别ID返回帖子:

public Post GetPostByCategory(Guid categoryId)
        {
            var query= _siteContext.Posts.Where(p => p.Category.Id == categoryId)
                                    .OrderByDescending(p => p.CreationDate);
            return query;//Error 
        } 

我只想返回查询,查询必须通过Post类型,我该怎么办?

我不想像这样返回帖子列表

 public IList<Post> GetPostByCategory(Guid categoryId)
            {
                var query= _siteContext.Posts.Where(p => p.Category.Id == categoryId)
                                        .OrderByDescending(p => p.CreationDate);
                return query.tolist(); 
            }

我之前通过Nhibernate完成了这样的somthine:

  public int TotalPostsForCategory(string categorySlug)
        {
          return _session.Query<Post>()
                        .Where(p => p.Published && p.Category.UrlSlug.Equals(categorySlug))
                        .Count();
        }

如何使用Entity Framework ???

2 个答案:

答案 0 :(得分:2)

您必须使用FirstOrDefault()扩展方法仅返回第一个元素:

public Post GetPostByCategory(Guid categoryId)
{
    var firstPost = _siteContext.Posts
                                .Where(p => p.Category.Id == categoryId)
                                .OrderByDescending(p => p.CreationDate)
                                .FirstOrDefault();
    return firstPost;
} 

FirstOrDefault将被SQL查询中的TOP 1替换 查询应该看起来像这样:

SELECT TOP 1 p.*
FROM Posts p
WHERE p.CategoryId = categoryId
ORDER BY p.CreationDate DESC

答案 1 :(得分:2)

您可以像这样使用FirstSingle

public Post GetPostByCategory(Guid categoryId)
{
  var query= _siteContext.Posts.Where(p => p.Category.Id == categoryId)
                         .OrderByDescending(p => p.CreationDate);
  return query.First();
}

public Post GetPostByCategory(Guid categoryId)
{
  var query= _siteContext.Posts.Where(p => p.Category.Id == categoryId)
                         .OrderByDescending(p => p.CreationDate);
  return query.Single();
}

请参阅http://msdn.microsoft.com/en-us/library/bb348657.aspxhttp://msdn.microsoft.com/en-us/library/bb156472.aspx