2016-10-27 44 views
-2

假設我有一個領域模型是這樣的:的最佳方式

public class Book 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Author { get; set; } 
    public DateTime PublicationDate { get; set; } 
    public DateTime EntryDate { get; set; } 
    public string EnteredBy { get; set; } 
} 

但我希望有一個視圖模型,以排除某些領域,如:

public class BookView 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Author { get; set; } 
    public DateTime PublicationDate { get; set; } 
} 

有兩種從數據庫中獲取視圖模型的方法。第一種方式是這樣的:

List<BookView> views = context.Books.Where(b=>b.Author=="Winston Churchill") 
    .Select(b=>new BookView() { ID=b.ID,Title=b.Title,Author=b.Author,PublicationDate=b.PublicationDate}) 
    .ToList(); 

和第二種方式是這樣的:

var results = context.Books.Where(b => b.Author == "Winston Churchill"); 
List<BookView> views = new List<BookView>(); 
foreach(var b in results) 
{ 
    views.Add(new BookView() { ID = b.ID,Title = b.Title,Author = b.Author,PublicationDate = b.PublicationDate});   
} 

我的問題是不會在所有問題對性能有什麼區別?後者將允許更多的層分離 - 例如Book模型可能只是在一個單獨的Data程序集中,根本不參考視圖模型。但是,我想知道Select子句是否使查詢更有效。

+0

如果條件不匹配,第一種方法將拋出異常。至於第二個,你總是可以檢查列表是否爲空。至於表現,這並不重要。我建議使用'for'循環而不是'foreach',對於大型集合來說要快一些。 –

+0

@Cristian Szpisjak它拋出了什麼異常?嘗試此代碼時,我沒有遇到異常情況。 – astidham2003

+0

@Matthew你有沒有試過性能測試或任何類型的性能測試?看過每種情況下生成的SQL嗎? – astidham2003

回答

2

「選擇」子句確實使它更具有表演性。 select是直接在數據庫上執行的,因爲它是一個IQuerable對象,因此您只能查詢select中的字段。另一種方法是,查詢所有列並在內存中操作它們。

+0

不知道performatic這個詞。即使我同意回答 – Fran

+0

performatic手段執行更好 – Stormhashe

+0

這個詞不存在。我認爲你正在尋找高性能。這甚至是有害的http://english.stackexchange.com/questions/38945/what-is-wrong-with-the-word-performant – Fran