2011-04-09 39 views
3

帽儿元素的数目我有两个数据模型博客。 BlogId是在实体框架4 - 如何从另一个表(通过外键连接)

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

    ... 
} 

外键现在这工作得很好,我的仓库是快乐和拉从DB期望的一切。

我的问题是 - 有没有办法限制数量的帖子得到检索。也许一些LINQ魔术?

这里是我目前在库的方法是这样的:

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

回答

3

可惜的是EFv4不提供简单的方法来限制导航返回的记录数属性。

如果您正在使用EntityObject派生实体,你可以使用这样的:如果你正在使用波苏斯

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

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

你必须为执行单独的查询(如果代理波苏斯你可以convert navigation propertyEntityCollection<Post>以访问到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和的DbContext API提供加载相关实体的只有数量有限的方式:

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

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

编辑:

你可以用投影做单查询:

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

要知道,你必须从匿名类型的第二paremeter访问的职位。

+0

谢谢拉迪斯拉夫。我正在使用POCO,而且我在这里做了类似于您的建议的事情。但是,如果我可以在一次去DB_的情况下做到这一点,我就会喜欢它。 – zuniga 2011-04-09 22:52:51

+0

@zuniga:我添加了单个查询的版本。 – 2011-04-09 23:12:42

+0

@Ldislav - 工作! – zuniga 2011-04-11 18:55:53

0

你的意思是:

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

我认为只需在结果(包含与博客相关的所有帖子)从数据库中提取后,只需选择_numberOfPosts_帖子即可。我希望实际上只能从数据库中提取_numberOfPosts_。 – zuniga 2011-04-09 06:11:45