Share via


WPF, MVVM & Data (in a nutshell)

***This is an article to summarize the concepts of WPF data manipulation, within the MVVM pattern.



The Model

The Model in MVVM is usually just the class (business object). A "Person" class has properties and methods relating only to that class. This class is not usually responsible for persisting to database or file. The database layer is not really anything to do with the actual MVVM pattern, it's just part of the plumbing, so to speak.

The ViewModel

The ViewModel uses the "database layer" to collect and present data (data of the object classes in Model). The returned data is held in public properties of the ViewModel, like (List<Person>) MyPersonel. A ListBox on your View can then bind to the ViewModel property, consume the data and two-way update it with no further code needed.

 

The Repository

The ViewModel could [for example] request data from a Repository (eg, a class in separate the "Repositories" folder). Then once the data is updated, you can use the same repository to same changes.

If you want full control, you can request the data and rebuild objects yourself, by hand. With some databases you have no choice. Here are a bunch of examples of connecting to an SQLite database, building objects and collections, saving back etc. All the usual database things you'd need for SQLite.

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/dd0c204d-090f-4ce7-883d-e3722eeb474a

 

DataAdapters

An alternative to this method is to use SqlDataAdapters, which bridge the gap. You then load DataTable.DefaultView into your DataGrid. Additions and changes are two-way bound back to the DataTable, and you use "adapter.Update()" to save the changes to the database.
 

Entity Framework

The MS recommended way is to use Entity Framework. I HIGHLY recommend this method, as it generates the database layer and exposes the database as objects. A Person table is exposed as a "Persons" collection that you can add and remove to, then update to save.Watch here.

 

Further reading 

If you haven't found it yet, one of the best introductions to MVVM is Josh Smith's MSDN mag article (especially The Data Model and Repository)
 


Please feel free to correct this article, or add to it.
It is one of the sources I give in answer to MSDN WPF Forum questions, regarding the subject.