2011-08-24 58 views
0

我正在嘗試編寫一個查詢,該查詢與主實體一起返回已過濾的關聯,並且似乎無法找到這樣做的整潔方式。實體框架查詢幫助 - 已篩選投影

我有一個文章實體和ArticleResource實體,使得一個文章可以包含許多ArticleResources

我想查詢前10名最近上傳的文章,並使用實體框架獲取每篇文章的前3名資源。

做到這一點的一種方法是獲得前10篇文章,然後迭代並獲取每篇文章的前3個資源。這種方法的工作,但不是最佳

任何人都可以建議我在Entity Framework 4.1中做到這一點的正確方法嗎?

回答

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