实体框架查询帮助 - 过滤投影

时间:2011-08-24 01:43:47

标签: entity-framework-4.1

我正在尝试编写一个返回过滤后的关联以及主实体的查询,但似乎无法找到一种巧妙的方法。

我有文章实体和 ArticleResource 实体,以便一篇文章可以包含多条ArticleResources 。< / p>

我想查询最近上传的10篇文章,并使用Entity框架获取每篇文章的前3个资源。

这样做的一种方法是获得前10篇文章,然后迭代并获得每篇文章的前3个资源。这种方法有效但不是最佳的

有人可以建议我在Entity Framework 4.1中使用正确的方法吗?

1 个答案:

答案 0 :(得分:0)

我不确定以下示例代码是否会回答您的问题

class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer<BlogContext>(new DropCreateDatabaseIfModelChanges<BlogContext>());

            BlogContext context = new BlogContext();

            for (int i = 1; i < 13; i++)
            {
                Article article = new Article() { Title = "article_" + i.ToString()};
                for (int j = 1; j < 5; j++)
                {
                    article.ArticleResources.Add( new ArticleResource { Name = "articleresource_" + i.ToString() + "_" + j.ToString() });
                }
                context.Articles.Add(article);
            }

            context.SaveChanges();

            var query = (from a in context.Articles.Include(a => a.ArticleResources)
                         orderby a.Id descending
                         select new ArticleViewModel { ArticleId= a.Id, ArticleTitle = a.Title, ArticleResources= (HashSet<ArticleResource>)a.ArticleResources.OrderByDescending(r=>r.Id).Take(3) })
                        .Take(10);

            Console.WriteLine(string.Format("article_id\tarticle_title\tarticle_resource"));

            foreach (var item in query.ToList())
            {
                Console.WriteLine(string.Format("{0}\t{1}", item.ArticleId, item.ArticleTitle));
                foreach (var ar in item.ArticleResources)
                {
                    Console.WriteLine("\t\t{0}\t{1}", ar.Id, ar.Name);
                }
            }

            Console.Read();
        }
    }

    public class ArticleViewModel
    {
        public int ArticleId { get; set; }
        public string ArticleTitle { get; set; }
        public HashSet<ArticleResource> ArticleResources { get; set; }
    }

    public class BlogContext : DbContext
    {
        public DbSet<Article> Articles { get; set; }
        public DbSet<ArticleResource> ArticleResources { get; set; }
    }

    public class Article
    {
        public Article()
        {
            ArticleResources = new HashSet<ArticleResource>();
        }
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual ICollection<ArticleResource> ArticleResources { get; set; }
    }

    public class ArticleResource
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ArticleId { get; set; }
        public virtual Article Article { get; set; }
    }