,如果你在一個大量數據的搜索,過濾用數據庫查詢,因爲數據庫通常會做的搜索相當快,可能會更快的數據。
此外,如果您將數據加載一次(進入RAM),當數據更改時,DataGrid將顯示無效數據。
最佳做法可能會寫一些DataService的功能,如:
List<ColumnType> GetColumn(int column)
{
var data = new List<ColumnType>();
using (var connection = new MyConnection())
{
//load data
}
return data;
}
在每個功能
連接和斷開到數據庫來獲取項目。但肯定把一個函數如GetSingle(ItemId)
放在一個循環中是一個錯誤。
爲了簡單起見,我建議使用較少耦合的方法,避免類之間的許多鏈接或使用靜態屬性。因爲通常它不會使數據保持顯着的性能並避免連接到數據庫。但是我無法確定,這取決於您的應用程序。
編輯:
如果你的數據庫文件非常小,你可以犧牲簡單的性能和一次加載所有數據,並存儲在RAM中。你也可以使用這樣的標準庫:
public class Repository<TModel> where TModel: class
{
public Repository<TModel>(Context context)
{
_context = context;
}
private Context _context;
...
public IEnumerable<TModel> Find(Expression<Func<TModel, bool>> where)
{
return _context.CreateObjectSet<TModel>().Where(where);
}
public IEnumerable<TResult> GetColumn(Func<TSource, TResult> selector)
{
return _context.CreateObjectSet<TModel>().Select(selector);
}
}
上下文是你把所有加載的數據。它應該有這樣一個泛型函數:
public class Context
{
private List<Customer> _customerList;
private List<Product> _productList;
public Context()
{
//Load All Lists here or in the following function instead
}
public List<TModel> CreateObjectSet<TModel>() where TModel : class
{
if (TModel is Customer)
{
//you can load _customerList here instead of in constructor
//check if _customerList is null then load it here for now and future use
return _customerList;
}
if (TModel is Product)
{
//check if _productList is null then load it here for now and future use
return _productList;
}
...
throw...
}
}
現在你可以使用lambda表達式方便地查詢您的上下文數據:
var repository = new Repository<Product>(context);
List<string> nameColumn = repository.GetColumn(x => x.Name);
我知道,如果我有巨大的數據庫就像你說的,我應該使用的方法。但在我的示例中,我有DBF文件中的小DB(大約<1MB),我只讀取數據,現在我不知道從RAM中讀取數據或每次從文件中讀取數據會更好(用於性能) 。 (有沒有像Repository這樣的模式?) 另外我想知道MVVM Messenger發送對象的限制。我儘可能發送小件物品,或者無所謂。 – pwroblew
由於這是一個小的一次加載,我認爲RAM選項工作得更快。我編輯了我的答案。 – Bijan