How to limit the number of related data using 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;
}

And I want to download all Catergories with my posts like this:

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

Now I want to limit the number of messages returned, can anyone show mw how to do this?

I am using EntityFramework 4.3.1

+3
source share
2 answers

Impossible to impatiently load ( Include) - impatient download always returns all related data. You must use predictions for an anonymous or new type (you cannot use existing mapped objects):

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

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

, .

+1

Source: https://habr.com/ru/post/1540482/


All Articles