如何使用Include限制相关数据的数量 [英] How to limit number of related data with Include

查看:158
本文介绍了如何使用Include限制相关数据的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Cat
{
   public int CatID;
   public string Name;
   public ICollection<Post> Posts;
}
class Post
{
   public int PostID;
   public string Name

   public int CatID;
   public virtual Cat Parent;
}

我想加载所有的Catergories与他们的帖子:

And I want to load all the Catergories with their Posts so:

var cats = context.Cat.Include(c => c.Posts);

现在我想限制返回的帖子数,有人可以显示mw怎么做?

Now I want to limit the number of Posts that are returned, can someone show mw how to do that?

我正在使用EntityFramework 4.3.1

I'm using EntityFramework 4.3.1

推荐答案

不可能加载( Include ) - 加载返回总是所有相关数据。您必须使用匿名或新类型的投影(您不能使用现有的映射实体):

It is not possible with eager loading (Include) - eager loading returns always all related data. You must use projections to anonymous or new type (you cannot use your existing mapped entities):

var cats = context.Cat.Select(c => new 
{ 
    Category = c, 
    Posts = c.Posts.OrderBy(p => p.Name).Take(10) 
});

这篇关于如何使用Include限制相关数据的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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