C# – MVVM and Entity Framework

MVVM – Model View ViewModel is the new design pattern originated from Microsoft, introduced by Martin Flower in 2004 and widely used after a publication of Josh Smith on MSDN magazine in 2009. MVVM is targeted at modern user interface development platforms such as WPF and Silverlight which are completely differently designed to traditional developer. Although MVVM bases on MVC – Model View Controller, the ViewModel is more better because it provides an easier way to expose and cosume data objects from the Model and therefore can handle the display logic of View. Despite of the great data binding functions of WPF, in MVVM we do not have to write any code in the View layer anymore. The View and Model layer are completely seperated which means the designers can use native WPF markup language XAML and create bindings to the ViewModel ,which is written by application developers, without writing any code behind the View. The designers can then focus on their designs rather than developing the business logic behind and therefore the software development can be better controlled,easier for bugfixing and transparenter. That’s short description about MVVM and its advantages. I think MVVM is not the hot topic anymore so if you want, you can find a lot of interesting articles on internet. In this blog post, I just want to try the MVVM Light Toolkit to generate automatically a MVVM application for me when I create a new application because until now I must create the pattern myself manually.

1. Go to http://mvvmlight.codeplex.com/ and download the latest version of MVVM Light Toolkit.
2. Open Visual Studio, go to Tools –> Options –> Projects and Solutions. Copy the template path (without the last folder). For example in the image below, only copy the selected part of the path

Projects and Solutions

3. Open the archive download package of MVVM Light Toolkit, extract the GalaSoft.MvvmLight.Templates.V3.VS10.zip to the folder above to install the template of MVVM application to Visual Studio.

If you want to read more about MVVM, you can read this book Building Enterprise Applications with Windows® Presentation Foundation and the Model View ViewModel Pattern

4. In Visual Studio, go to Tools –> Code Snippets Manager. Copy the location path as image below

Code Snippets Manager

5. Open the archive download package of MVVM Light Toolkit, extract the GalaSoft.MvvmLight.Snippets.V3.zip to the copied path above so that we can use the snippets to create code faster.

6. In download package of MVVM Light Toolkit, extract GalaSoft.MvvmLight.Binaries.V3.zip to C:\ to install the binary files. Now restart Visual Studio to apply all changes.

7. After installing MVVM Light Toolkit, you’ll see in Visual Studio new templates when creating a new project. Choose MVVMLight (WPF), enter a name for project and discover what there are in this type of project.

8. In the Solution Explorer we see there are 3 folders: Model, Skins and ViewModel. Model contains data objects, Skins consits of all user defined templates and ViewModel defines all of business logics for application.

MVVM folders

So let’s take a look at the source code of MainWindow class

public partial class MainWindow : Window
{
	/// <summary>
	/// Initializes a new instance of the MainWindow class.
	/// </summary>
	public MainWindow()
	{
		InitializeComponent();
		Closing += (s, e) => ViewModelLocator.Cleanup();
	}
}

There’s only one row of user code to clean up all objects before closing and nothing else. Now let’s look at the XML code

<Window x:Class="MvvmLight1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Height="300"
        Width="300"
        Title="MVVM Light Application"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">

        <TextBlock FontSize="36"
                   FontWeight="Bold"
                   Foreground="Purple"
                   Text="{Binding Welcome}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   TextWrapping="Wrap" />

    </Grid>
</Window>

The data context of form is bound to MainViewModel (it stands only Main but the class in source code should be MainViewModel) and its text block is bound with a property of MainViewModel which is called “Welcome”. Jump to MainViewModel class in folder ViewModel we’ll see there is a property “Welcome” whose text is “Welcome to MVVM Light”. It’s great, isn’t it? Without writing any code in View class (MainWindow.cs), just binding the form with a view model and each control with each property, we can manipulate the content of its control. What’s a beautiful seperation!

9. Ok now it’s time to build more features into the sample application. I have the sample database AdventureWorks at my local machine. I’ll try now to connect to this database and execute some CRUD operations on it through this MVVM application. If you still do not have this one, then download it here http://msftdbprodsamples.codeplex.com/. Then Right click on Model folder, choose Add –> New item –> ADO.NET Entity Data Model –> … establish a connection with AdventureWorks database and choose only 2 tables to make a demo: Contact and Employee. After finishing this step we have something like this

ADO.Net Entity Data Model

10. We have now our data objects in Model folder. As a designer, I would like to display a list of “Contact” on a list view with some detailed information of each contact. So I would browse to XAML Code and insert a ListView and Button like code below

<ListView Grid.Row="0" ItemsSource="{Binding ContactsList}" IsSynchronizedWithCurrentItem="True">
	<ListView.View>
		<GridView>
			<GridViewColumn DisplayMemberBinding="{Binding LastName}" Header="Last name" Width="90" />
			<GridViewColumn DisplayMemberBinding="{Binding FirstName}" Header="First name" Width="90"/>
			<GridViewColumn DisplayMemberBinding="{Binding Employee.Count}" Header="Employee count" Width="100"/>
		</GridView>
	</ListView.View>
</ListView>
<StackPanel Orientation="Horizontal" Grid.Row="2">
	<Button Content="Load" Height="23" Name="btnLoad" Width="75" Command="{Binding LoadCommand}" />
</StackPanel>

With the code above I would like to bind the ItemsSource of ListView to property ContactsList of MainViewModel, the columns of list view to the property “LastName”, “FirstName” and “Employee.Count” of each item. The button “Load” would be bound with the Command “LoadCommand”. You can see that we can not only bind to normal property but also to the sub-property. In the 3. column of list view, I bind firstly to “Employee” property of each “Contact” and then bind forward to “Count” property of “Employee”.

The bindings are easy to understand, aren’t they? Form will be bound with a ViewModel, the controls on form will be bound with Property of view model, each property of controls can be again bound with the sub-property of each property in ViewModel. Follow this structure then we’ll have a wonderful MVVM application.

11. Now I am developer for business logic. I should give the View what he needs. At first he need a list of contacts binding to ContactsList property

/// <summary>
/// The <see cref="ContactsList" /> property's name.
/// </summary>
public const string ContactsPropertyName = "ContactsList";
private ObservableCollection<Contact> contactsList = null;
/// <summary>
/// Gets the Employees property.
/// TODO Update documentation:
/// Changes to that property's value raise the PropertyChanged event.
/// This property's value is broadcasted by the Messenger's default instance when it changes.
/// </summary>
public ObservableCollection<Contact> ContactsList
{
	get
	{
		return contactsList;
	}

	set
	{
		if (contactsList == value)
		{
			return;
		}

		var oldValue = contactsList;
		contactsList = value;

		// Update bindings, no broadcast
		RaisePropertyChanged(ContactsPropertyName);

	   }
}

I created the property above through the install snippets. Just enter “mvvminpc” in code editor, press Tab to insert property automatically and then Tab again to jump through each field of property and edit them as you want. After creating a list of contacts for list view, I need to feed the Load button

private ICollectionView contactsView;
private RelayCommand loadCommand;
public ICommand LoadCommand
{
	get
	{
		if (loadCommand == null)
			loadCommand = new RelayCommand(() => Load());
		return loadCommand;
	}
}
private void Load()
{
	ContactsList = new ObservableCollection<Contact>((from contact in awContext.Contact.Include("Employee")  where contact.LastName.StartsWith("ng") select contact));
	contactsView = CollectionViewSource.GetDefaultView(ContactsList);
	if (contactsView != null)
		contactsView.CurrentChanged += new System.EventHandler(contactsView_CurrentChanged);
	RaisePropertyChanged("CurrentContact");
}

void contactsView_CurrentChanged(object sender, System.EventArgs e)
{
	RaisePropertyChanged("CurrentContact");
}

In the block code above, I define LoadCommand as a RelayCommand with action Load(). When user clicks on button Load, the action Load() will be called. The ContactsList will be fullfilled with the data got from database and limited to only contacts with LastName.StartsWith(“ng”). We know that loading from database without limitation requiring the database server more time and performance to give the result back and then a lot of time to map this information into data model. Therefore I just load some of contacts and show on the list view. Of course you can edit the Load() function to load more items.

MVVM and Entity Framework

Now we have a working application with a simple function that loads information from database and shows it on form. With the miracle of MVVM, we do not have to write any code to expose data and control the display logic of View class. That mean we can make a meeting with designer and coder to arrange how the ViewModel should be to make this relation work and then the designer can design the UI independently of the coder. Especially it’s really good for developer like me who is very, very bad at design. ^_^. From now on, I can push the design work to my colleague who has better design skills and concentrate to the business logic behind.
In the complete soure code “MVVM and Entity Framework” you can find more command to create, update and delete contact from database. However it’s just a sample application therefore I try to keep it as simple as possible. No complicate code.

Leave a Reply

Your email address will not be published. Required fields are marked *