2009-08-12 52 views
0

有兩個類,如博客和發佈,在實體框架(和LINQ到實體),如何獲得按日期排序的博客。我得到了與博客帖子這樣說:如何獲得使用實體框架爲ASP.NET MVC排序的相關對象

from blog in db.BlogSet.Include("Posts") select blog 

,現在我不得不這樣做:

public class BlogAndPosts { 
    public Blog Blog { get; set; } 
    public IEnumerable<Post> Posts { get; set; } 
} 

from blog in db.BlogSet 
select new BlogAndPosts() { 
    Blog = blog, 
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime) 
} 

,這是非常令人費解的和醜陋的。我創建BlogPosts類的原因是現在,因爲我必須將兩個變量Blog和Posts傳遞給MVC,所以我需要一個視圖模型。

我甚至很想嘗試這個技巧:

from blog in db.BlogSet 
select new Blog(blog) { 
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime) 
} 

但什麼是做了正確的方法是什麼?實體框架不是MVC的方式嗎?

回答

2

我通常會創建一個完全不知道實體框架並投影到其中的演示模型類型。所以我會這樣做:

public class PostPresentation { 
    public Guid Id { get; set; } 
    public string Title { get; set; } 
    public DateTime PostTime { get; set; } 
    public string Body { get; set; } 
} 

public class BlogHomePresentation { 
    public string BlogName { get; set; } 
    public IEnumerable<Post> RecentPosts { get; set; } 
} 

from blog in db.BlogSet 
select new BlogHomePresentation 
{ 
    BlogName = blog.name, 
    RecentPosts = (from p in blog.Posts 
        order by p.PublicationTime desc 
        select new PostPresentation 
        { 
         Id = p.Id, 
         Title = p.Title, 
         PostTime = p.PublicationTime, 
         Body = p.Body 
        }).Take(10) 
} 

這是否看起來像很多工作?考慮優點:

  1. 您的演示文稿完全無知的持久性。不是「無知,因爲在必須使所有的屬性public virtual」,但完全無知。
  2. 現在可以在設計數據庫模式之前設計演示文稿。在事先沒有做太多工作的情況下,您可以獲得客戶的批准。
  3. 演示模型可以設計爲適合頁面的需求。您不必擔心急切的加載或延遲加載;您只需編寫模型以適應頁面。如果您需要更改頁面或實體模型,您可以執行其中一個,而不會影響另一個。
  4. 簡單類型的模型綁定更容易。這種設計不需要自定義模型綁定器。
+0

只是爲了記錄,我不認爲這樣做是有道理的,除了解決方法實體框架。使用任何其他ORM我不會提取相關的對象,並把它們放在一個類中;儘管如此,我會把一個完全獨立的數據放進去。無論如何,它是有效的,所以我接受它。 – Pablo 2010-05-22 08:51:17

0

我也建議使用視圖模型。當你的應用程序的增長,有可能是在一個特定的觀點更多的內容,如:

public class PostDetailResult { 
    public Post<Post> Post { get; set; } 
    public IList<Post> RecentPosts { get; set; } 
    public IList<Post> RelatedPosts { get; set; } 
    public IList<Post> MostRated { get; set; }  
} 

您可以添加控制器和像庫中的數據抽象之間的另一層,因爲你的BL應該決定什麼「MostRated」職位。如果您在多個視圖中使用「MostRated」帖子,則不希望在多個控制器中編寫相同的查詢。使用存儲庫,控制器代碼可能如下所示:

var result = new PostDetailResult { 
    Post = repo.GetPost(id), 
    RecentPosts = repo.GetRecentPosts(), 
    RelatedPosts = repo.GetRelatedPosts(id) 
}; 

希望,這有幫助。

相關問題