2
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与他们的帖子这样:如何限制与包括

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

现在我要限制返回文章的数量,可以一个人显示mw如何做到这一点?

我使用的EntityFramework 4.3.1

回答

11

这是不可能的预先加载(Include) - 预先加载的回报总是所有相关数据。您必须使用预测,以匿名或新的类型(你不能使用你现有的映射实体):

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

不能使用投影与Include()方法,但要注意的是,在下面的查询就可以限制使用名称返回类别的数量领域的职位。你

using (var context = new YourContext()) 
{ 
    var categories = from c in context.Categories.Include("Posts") 
        where c.Posts.Any((p)=>p.Name == "Linq") 
        select c; 
} 

也可以做这样的事情:

context.Categories 
     .Select(c => new { 
         Category = c, 
         Posts = c.Posts.Where(p => p.Name == "Linq") 
     }).AsEnumerable() 
     .Select(cp => cp.Category); 

希望它能帮助。