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

查看:26
本文介绍了如何使用 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;
}

我想用他们的帖子加载所有的猫(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) 
});

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

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