我是MVVM的新手,我想知道如何使用Messenger和数据服务。
我有一个dataService类和方法GetAll从DBF文件加载数据。所有数据都以DataGrid显示。文件的路径由OpenFileDialog选择。当我转到另一个视图时,我只需要一个小的安静(一列)的数据。现在,我想知道如何在另一个viewModel中获取这些数据:
我还想知道如何几次获取数据。如果我有GetAll方法,那么我就有了所有数据的对象。我能要这样的东西吗?
class DataService : IDataService
{
List<T> _allData = new List<T>();
List<T> getAll()
{
...
_allData = ...
return _allData;
}
}现在,如果我有另一种方法,我可以使用集合_allData,而不必每次需要一些数据时都要连接don或文件。
但在某些项目中,我看到每个方法都与DB有连接。什么是最佳做法?
(如果我的问题混乱,对不起;)
发布于 2013-10-08 21:43:53
如果您在大量数据中搜索,使用数据库查询对数据进行过滤可能会更快,因为数据库通常会非常快地进行搜索。
另外,如果您将数据加载一次(到内存中),则当数据被更改时,DataGrid将显示无效数据。
最佳实践可能是编写几个DataService函数,如:
List<ColumnType> GetColumn(int column)
{
var data = new List<ColumnType>();
using (var connection = new MyConnection())
{
//load data
}
return data;
}在每个函数中,连接和断开数据库以获取项。但是,将像GetSingle(ItemId)这样的函数放在循环中肯定是错误的。
我建议采用少耦合的方法,避免类之间的许多链接,或者为了简单起见使用静态属性。因为通常情况下,保存数据和避免连接到数据库并不能显着地提高性能。但是,我不能确定,这取决于您的应用程序。
编辑:
如果您的Db文件非常小,您可以为了性能而牺牲简单性,并一次加载所有数据并将其存储在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);https://stackoverflow.com/questions/19253976
复制相似问题