WPF and MVVM tutorial 02, The model.

In the first part of this tutorial we saw the MVVM model and how it works.

In this part of our tutorial we will work directly with the Entity Model and LinqToSQL. I am using a database-first approach so in my opinion using LinqToSQL will be better then Entitiy Framework. I am going also to show you an easy way to build a custom Unit Of Work to manage the context status with Linq 2 SQL.

The Visual Studio Project.

First of all open a blank Visual Studio solution, I called it WPF.Tutorial.VMMV. Add two projects on it: 1) WPF Application …UI and 2) Class Library (…DAL).

The final layout should be this one (in my picture the model is already inside).

New Picture (8)

The Data model.

If you have installed the Adventure Works database in the past you already know what I am talking about. The model I will use in the tutorial will come up with this layout:

New Picture (7)We will have a customer with the personal information and the related orders with the order information.

Go into the DAL project and from the menu choose add new file –> LinqToSQL and call it DataModel. Now you need to connect you data model into your AW database and drag in the design pane the tables you need. At the end you should come up with the same layout I have in the previous picture.

The Unit of Work.

If you do not what I am talking about, this is the explanation by Martin Fowler.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.

Of course with LinqToSQL we do not need a Unit of Work because L2S by itself is the data context, but because it is not able to manage the disposing in a good way, here are my 2 cents about.

We need a contract, in this way an interface in the DAL that will implement the Unit of Work:


First of all let’s build the C.R.U.D. implementation into a simple interface. In this case I am going to use the generics and the Linq expression because my project will work only with Linq so I do not need an high level of abstraction:

Now we need the real Unit of Work that will inherit from our contract. We want also to inherit from IDisposable because otherwise we will not be able to keep alive our datacontext during the crud operations.

Now, the second step is to translate the UoW in something readable for Linq:

Now we have a complete Unit of Work that we will use in each repository. Ops I forgot to mention that we will not have a real repository in our solution but a view model …