如何使用 Include 限制相关数据的数量

人气:643 发布:2022-10-16 标签: include entity-framework entity-framework-4 ef-code-first

问题描述

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;
}

我想用他们的帖子加载所有的猫(egories):

And I want to load all the Cat(egories) with their Posts so:

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

现在我想限制返回的帖子数量,有人可以告诉我怎么做吗?

Now I want to limit the number of Posts that are returned, can someone show me 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) 
});

420