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

希望它能幫助。