2016-02-13 23 views
0

我有一個視圖模型看起來是這樣的:是否可以在實體框架中使用單個查詢獲取多個數據類型?

public int AllRecords { get; set; } 
public int IsActiveRecords { get; set; } 
public int IsDeletedRecords { get; set; } 
public List<Setup_Country> Countries { get; set; } 

enter image description here

是否有可能編寫出使用實體框架來獲取這些數據從數據庫 單個查詢?

如果不是,那麼做到這一點的最佳方法是什麼?

+0

是第3個屬性所有的計數,主動和刪除'Setup_Country'項目? –

+0

是的。這將計算指定的記錄。 –

+1

爲什麼不只是'var countries = db.Setup_Countries.ToList(); var model = new ViewModel {Countries = countries,AllRecords = countries.Count,IsDeletedRecords = countries.Count(x => x.IsDeleted),...}' –

回答

1

你想要的多樣性是多少?您可以填寫該視圖模型是這樣的:

model = new MyViewModel(); 
model.Countries = db.SetupCountry.ToList(); 
model.AllRecords = model.Countries.Count(); 
model.IsActiveRecords = model.Countries.Count(c => c.IsActive); 
model.IsDeletedRecords = model.Countries.Count(c => c.IsDeleted); 

正如斯蒂芬·馬克在評論中指出的那樣,這將查詢數據庫只有一次。

或者,如果你想要一個班輪,

model = new MyViewModel{ 
    Countries = db.SetupCountry.ToList(), 
    AllRecords = db.SetupCountry.Count(), 
    IsActiveRecords = db.SetupCountry.Count(c => c.IsActive), 
    IsDeletedRecords = db.SetupCountry.Count(c => c.IsDeleted), 
} 
+0

你能告訴我哪一個是最好的方法嗎? –

+1

第一個,因爲它只需要將db存儲一次,並依靠內存進行操作,所以它的效率更高。 –

相關問題