假設我有一個領域模型是這樣的:的最佳方式
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
子句是否使查詢更有效。
如果條件不匹配,第一種方法將拋出異常。至於第二個,你總是可以檢查列表是否爲空。至於表現,這並不重要。我建議使用'for'循環而不是'foreach',對於大型集合來說要快一些。 –
@Cristian Szpisjak它拋出了什麼異常?嘗試此代碼時,我沒有遇到異常情況。 – astidham2003
@Matthew你有沒有試過性能測試或任何類型的性能測試?看過每種情況下生成的SQL嗎? – astidham2003