Entity Framework 4 - How to cap the number of child elements from another table (connected via a foreign key)

我怕爱的太早我们不能终老 提交于 2019-12-12 09:53:13

问题


I have two data models Blog and Post. BlogId is a foreign key on the Post table

public class Blog
{
   public int ID { get; set; }

   public string Title { get; set; }

   public virtual ICollection<Post> Posts { get; set; }

  ...  
}


public class Post
{
   public int ID { get; set; }

   public virtual int BlogId { get; set; }

   public string Title { get; set; }

  ...  
}

Now this works fine and my Repository is happy and pulls everything as expected from DB.

My question is - Is there a way to limit the number of Posts that get retrieved. Perhaps some LINQ magic?

Here is what my current method in the repository looks like:

public Business FindBlog(int id)
{
    return this.context.Get<Blog>().SingleOrDefault(x => x.ID == id);
}

回答1:


Unfortunatelly EFv4 doesn't offer easy way to limit number of returned record for navigation property.

If you are using EntityObject derived entities you can use something like:

var blog = context.Blogs
                  .Single(b => b.Id == blogId);

var posts = blog.Posts
                .CreateSourceQuery()
                .OrderByDescending(p => p.Date)
                .Take(numberOfRecords)
                .ToList();

If you are using POCOs you must execute separate query for that (in case of proxied POCOs you can convert navigation property to EntityCollection<Post> to get access to CreateSourceQuery):

var blog = context.Blogs
                  .Single(b => b.Id == blogId);

var posts = context.Posts
                   .Where(p => p.BlogId == blogId)
                   .OrderByDescending(p => p.Date)
                   .Take(numberOfPosts)
                   .ToList();

EFv4.1 and DbContext API offers the way to load only limited number of related entities:

var blog = context.Blogs
                  .Single(b => b.Id == blogId);

context.Entry(blog)
       .Collection(b => b.Posts)
       .Query()
       .OrderByDescending(p => p.Date)
       .Take(numberOfPosts)
       .Load();

Edit:

You can do it in single query with projection:

var blog = context.Blogs
                  .Where(b => b.Id == blogId)
                  .Select(b => new 
                      {  
                          Blog = b,
                          Posts = b.Posts
                                   .OrderByDescending(p => Date)
                                   .Take(numberOfRecords)
                      })
                  .SingleOrDefault()

Just be aware that you must access posts from second paremeter of anonymous type.




回答2:


Do you mean:

public List<Post> GetBlogPosts(Blog blog, int numberOfPosts)
{
    return blog.Posts.Take(numberOfPosts);
}


来源:https://stackoverflow.com/questions/5602371/entity-framework-4-how-to-cap-the-number-of-child-elements-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!