WPF Dapper and MySQL a Simple Example
In this project we will create a simple WPF application which contains a DataGrid which is populated from a MySQL database. This is a halfway house between fully defining the connection and queries to using Entity Framework which is a magic black box. Dapper manages some of the magic but still allows us to manually define some aspects, removing some of the risk to a black box solution.
NuGet Packages
For this project we will need two packages;
- Dapper
- MySql.Data
NuGet Packages
MySQL Database, Tables, and User
I’m using MariaDB Community Server for this example, which can be downloaded from the following link. After completing the installation i created a new Database called ‘testdb‘ and then created a table called ‘testtable‘. The table has two attributes ‘ID‘ (Primary Key, Not NULL, Auto Increment) and ‘Name‘ (Varchar(50), Not NULL), with a few rows of data.
To access the data I also created a new user with Select, Delete, Insert and Update permissions for only the new table. Each set of tables for an application must have a new user with limited permissions, to maintain security and stop cross application access to the data.
Database and Table
WPF Application
Within Visual Studio create a new WPF Application in .Net Core 5.0.
Data Model
The model represents the data structure of the database table, this is sometimes referred to as the Data Transport Object (DTO) and can contain mapping from the database table attributes to the property’s within the DTO. Although it’s highly recommended that the DTO should be a one to one mapping of the database table, to keep things simple. The model can be identical to the DTO, and is in this case, normally it represents the data model that best fits the data across multiple applications or at the enterprise level. There is one more type of model which is the View Model which contains the business logic for the model within a specific applications architecture.
Our Model / DTO is very simple with two property’s, that will be used to read / write data to / from the database table.
app.config
The app.config is not a part of the standard WPF project, however it can be created by inserting a new JSON file. This file will be used to store the connection string for the application. This way it can be edited manually once the application is compiled allowing it to be manually configured based on the environment.
Helper
The Helper class allows us to recover the connection string based on its name.
Queries
In this case I’m using a static class to hold all of the queries for the project.
DataAccess
Now for the main meet and potatoes of the project, Data Access, here I where we need to import via NuGet Dapper, and MySql.Data. Dapper provides a set of API such as Query QueryAsyn, Execute ,ExecuteAsyn etc, that can take in our raw SQL Query and return a collection of objects in the case of Query.
MainWindow.xaml
We can now set up our Data Grid, and bind it to an Observable collection which implements INotifyCollectionChanged, and INotifyPropertyChanged which are required when binding a property.
MainWindow.xaml.cs
I’m not being a purist here as far as MVVM, I just wanted to keep it simple in this case and illustrate the usage of Dapper and MySQL.Data. So in the Main Window we will set the Data Context to this and call the Data Access object passing in the name of the connection to be used.
Result
Below we can see the simple result.
Final Result
Stored Procedure
We can also create stored procedures within the database, instead of having to recompile the application every time we want to make a change to a query.
Stored Procedure
Calling the Stored Procedure from the Code
To call the stored procedure we need to tell the Query command that it’s calling a stored procedure by specifying the command type as Stored Procedure.
Then in the Query’s class we will add a query an additional query which is just the name of the stored procedure. This is preferable as we can easily update the query in the database without rebuilding and distributing the application.
Calling Stored Procedure with Parameters
The new stored procedure takes in a VARCHAR(50) parameter ‘Param1‘.
Stored Procedure with Parameters
To call the stored procedure we need to tell the Query command that it’s calling a stored procedure by specifying the command type as Stored Procedure. Also the new stored procedure needs a parameter value this is passed as a generic class that’s constructed on the fly.
Again in the Query’s class we need to just pass in the name of the stored procedure.
Here we can see the result where the filtered data from the stored procedure is displayed.
Final Result
Programming pages
MySQL is a popular free database which many (including me) prefer for writing database applications. Being relatively new to WPF, I wanted to see how MySQL could be used in a WPF application. This proved to be a fairly long journey, so we’ll probably need several posts to get through it all.
First, if you’re new to MySQL, you’ll need to download and install it. I won’t go into great detail here, apart from pointing you in the direction of the main download page for the free version (there are commercial versions that cost real money as well). After installing MySQL itself, you’ll need to install the MySQL ADO.NET connector in order to use it in WPF programming. This is currently located here, but if in the future this link is dead, just do a search for MySQL and ADO.NET.
With these two packages installed you should be ready to start writing code in Visual Studio (VS). The program I’ll discuss is a front end to an existing database, which allows you to insert, modify and delete records in the database. In homage to Sheldon Cooper, the database will contain details of my comic book collection. I’ll assume that you understand the basics of database construction, including the creation of tables and insertion of records into these tables. I’ll also assume you know the rudiments of SQL, since I’ll be using it to construct a few commands to be sent to the database. If you don’t know SQL very well (or at all) it shouldn’t hamper you too much since you can probably figure out what the commands are doing (SQL is fairly transparent at this level).
First, we’ll need to consider the structure of the database itself. It contains three tables, which contain the following fields:
Publishers (publishers of comic books)
- Key_Publishers (the primary key)
- Name (the name of the publisher)
Titles (titles of comic book series, not of individual issues)
- Key_Titles (the primary key)
- Title (the title’s name, such as Action Comics)
- Publisher (an int giving the key of the publisher of this title)
Issues (individual issues of given titles)
- Key_Issues (the primary key)
- IssueTitle (the title of the individual issue)
- Title (an int linking to the key in the Titles table)
- Volume
- Number
- IssueDay
- IssueMonth
- IssueYear
- ComicVine (the URL of the page on http://www.comicvine.com giving details about this issue)
The UI of the program consists of a tab control with three tabs: one for editing the issues, one for the titles and one for the publishers. We’ll consider the issues one first. It looks like this:

At the top is a ComboBox from which we can choose the title. Beneath this is a DataGrid in which we display the individual records from the data base for that title. At the bottom are a few boxes in which individual data for the selected issue are displayed. The user can edit the information either directly in the DataGrid, or by editing the boxes at the bottom. The info in the boxes is identical to that displayed in the DataGrid except for the ComicVine link, which is shown as a URL in the text box, but as a hyperlink with the label ‘ComicVine’ in the DataGrid. This is done because the URL is usually far too long to be displayed conveniently in the grid, as you can see. The ‘Add’ button allows the user to add a new issue.
Clearly there’s a lot going on here, so we’ll need to take things step by step. To begin, let’s see how we can get the ComboBox to display the list of titles. (I’ll assume you can create the basic UI using Expression Blend (EB) or VS so I won’t go into that here.)
First, we need to let our VS project know we’ll be using MySQL. If you’ve installed the connecter mentioned above, you still need to include MySQL as a reference in your VS project. To do this, right-click on References in Solution Explorer and then click on the .NET tab. You may need to wait a few seconds while this list finishes loading, but eventually you can find MySQL.Data in the list, so you should add that. Now we can start writing some code.
Most of the linkage between controls and the MySQL database is done via data binding, which we’ve already looked at for simpler cases (see the index for a list of pages). Before we dive into the code it’s essential that you understand the structure of the program.
Ultimately the data are stored in the MySQL database, but the program itself doesn’t use this for the displays. First, the data must be loaded from the MySQL database into an internal data structure, which is then used for the main working of the program. Changes made by the user to the data using the UI affect only this internal representation of the data. If we want these changes to be made permanent, we need to write the code that will save these changes back to the original MySQL database.
WPF provides several internal data structures useful for storing information from a database. In fact, VS provides an automated way of creating a DataSet from database servers it has access to. Although you can create a DataSet from a MySQL server, the associated functionality provided by VS doesn’t seem to work with MySQL (at least I couldn’t find any way of making it work – there may be something that I haven’t discovered), so we need to write our own code to handle changes to the MySQL database. This isn’t that hard to do as we’ll see, but we’re getting ahead of ourselves.
Let’s see how we can access the data required to populate the ComboBox containing the list of Titles. From the above structure of the database, we see that the information is stored in the Titles table, so we need to load that data into the program. We’ve provided a separate class that handles this, and here’s the relevant code:
Note the ‘using’ statement that specifies the MySql library.
To get at data in a MySQL database we first need to connect to it, and that’s what the MySqlConnection is for. Its constructor requires a string giving the information needed to connect. In this case, we specify the server as ‘localhost’ which means it’s on the local machine. If you’re connecting to a remote server, you’d give the URL instead. The userID (uid) and password (pwd) are then given, followed by the name of the database.
Next, we need to create a MySqlDataAdapter, which is what does the actual work of retrieving the information from the database and storing it in the local object. In order for the adapter to get some data, it needs to know what to look for, and that’s what the ‘query’ string is for. This is an SQL command, which we’ll get to in a minute.
The adapter has to be given an object in which to store the data it retrieves. The standard data structure is the DataTable (in System.Data), which is essentially a single table of data. The Fill() method of MySqlDataAdapter executes the query on the MySQL database and loads the result in the DataTable. The DataTable will have columns with the same names as those in the original database, and it is these column names that can be used in data binding later on.
The last thing we do is define a sorting condition. Remember that whenever we bind a control to a data source such as a list, a collection view is automatically created and inserted between the data source and the control. This also applies to data binding between a control such as a ComboBox and a DataTable. The ComboBox displays the data as given by the collection view, so if we wish to sort the data as displayed in the UI, we add a sort command to the view. The data in the original DataTable is unchanged; all that changes is the way that data appears on screen.
In the case of a DataTable, we access its DefaultView as shown in the code, and then attach a Sort command to the view. The Sort is simply a string giving the sorting command we want. If we wish to sort the list of Titles, for example, we would specify ‘sortBy’ as “Title”, which is the name of the column we want to use as the sort key. (More complex sorting can be done too. We’ll see this when we consider the DataGrid showing the issues.)
There’s an important point here. Those of you familiar with SQL will know that we can include a sorting command as part of an SQL query, so you might be wondering why we didn’t just include the sorting command as part of the ‘query’ we sent to the database. The reason is that doing it this way would ask the MySQL database to do the sorting, so that the data used to populate the DataTable would be correctly sorted when it first arrives. However, if we then add extra rows to the DataTable by using our program, these rows would merely be tacked onto the end of the DataTable and would not be correctly sorted, since the DataTable hasn’t been told to sort its data. By putting the sort command into the DataTable rather that in the original SQL command, we ensure that the data as displayed in the program are always correctly sorted.
OK, we now have our internal DataTable, so how do we use this to populate the ComboBox? Fortunately, we’ve already considered data binding with a ComboBox, so we can model our code along that example. We’ll do things a little differently here, however, to illustrate a common technique for providing data sources in data binding.
We saw above that we provided the code for getting the DataTable in a class called DatabaseTable. We can access the DataTable by declaring an ObjectDataProvider in the XAML part of the code. In the Window.Resources section of the XAML, we can write:
This creates a resource with the name given as the Key (TitlesTable) by creating an object of the given type (DatabaseTable) and calling the indicated method (GetTable). The parameters passed to the method are given next, and in this case are two strings. The first string is the query to be sent to the MySQL database, and the second string is the Sort command, so that the DataTable sorts the records by Title.
Note that you’ll need to ensure that the various prefixes used in this XAML code are defined. Typically most of them are defined for you when you create a project in VS, but there are a couple that you’ll probably need to define yourself. Here, the ‘local’ namespace is the namespace used for the code in the project (Comics here). The ‘s’ namespace is required to define the String data type. (This is one reason why I hate XAML: although it is more compact in some cases, there is so much finicky stuff that it can be hard to get it right.)
We’re almost there. The last thing we’ll look at in this post is how to define the ComboBox so it gets its data from the ObjectDataProvider we just defined. The relevant line is:
There’s a bit of stuff in here that we’ll get to later, but the relevant bits are:
- ItemsSource is bound to the StaticResource TitlesTable that we just defined. This means that the items displayed in the ComboBox are bound to the items in that DataTable.
- DisplayMemberPath is specified as ‘Title’. Since the DataTable contains more than one (two, actually) columns, we need to tell the ComboBox which column to display. The ‘Title’ is the textual title which the user can read.
- SelectedValuePath: internally, we use the Key_Titles column for connecting a title with an issue (as we saw in the database tables above), so when the user selects an item from the ComboBox, we need to know the Key_Titles value in order to be able to retrieve the issues for that Title. More on this later when see how to populate the DataGrid.
- SelectionChanged: when the user selects an item in the ComboBox, we need to update the display in the DataGrid to display all issues with that Title, so we provide an event handler to do this. Again, we’ll see how this works in a later post.
The program at this stage should display the list of titles in the ComboBox, although selecting an item won’t do anything yet. But that’s enough for one post, so we’ll continue the story in the next post.
Name already in use
visualstudio-docs / docs / data-tools / create-a-simple-data-application-with-wpf-and-entity-framework-6.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Create a simple data application with WPF and Entity Framework 6
[!WARNING] If you’re using Visual Studio 2022, you should use Visual Studio 2022 version 17.3 Preview 3 or later for this tutorial. . moniker-end
This walkthrough shows how to create a basic «forms over data» application in Visual Studio. The app uses SQL Server LocalDB, the Northwind database, Entity Framework 6 (not Entity Framework Core), and Windows Presentation Foundation for .NET Framework (not .NET Core or .NET 5 or later). It shows how to do basic databinding with a master-detail view, and it also has a custom Binding Navigator with buttons for Move Next, Move Previous, Move to beginning, Move to end, Update and Delete.
This article focuses on using data tools in Visual Studio, and does not attempt to explain the underlying technologies in any depth. It assumes that you have a basic familiarity with XAML, Entity Framework, and SQL. This example also does not demonstrate Model-View-ViewModel (MVVM) architecture, which is standard for WPF applications. However, you can copy this code into your own MVVM application with few modifications.
The final code for this tutorial may be found in GitHub at VS Tutorial Samples — EF6.
Install and connect to Northwind
This example uses SQL Server Express LocalDB and the Northwind sample database. If the ADO.NET data provider for that product supports Entity Framework, it should work with other SQL database products just as well.
If you don’t have SQL Server Express LocalDB, install it through the Visual Studio Installer. In the Visual Studio Installer, you can install SQL Server Express LocalDB as part of the Data storage and Processing workload, or as an individual component.
Install the Northwind sample database by following these steps:
In Visual Studio, open the SQL Server Object Explorer window. (SQL Server Object Explorer is installed as part of the Data storage and processing workload in the Visual Studio Installer.) Expand the SQL Server node. Right-click on your LocalDB instance and select New Query.
A query editor window opens.
Copy the Northwind Transact-SQL script to your clipboard. This T-SQL script creates the Northwind database from scratch and populates it with data.
Paste the T-SQL script into the query editor, and then choose the Execute button.
After a short time, the query finishes running and the Northwind database is created.
Configure the project
In Visual Studio, create a new C# WPF App (.NET Framework) project.
Add the NuGet package for Entity Framework 6. In Solution Explorer, select the project node. In the main menu, choose Project > Manage NuGet Packages.
In the NuGet Package Manager, click on the Browse link. Entity Framework is probably the top package in the list. Click Install in the right pane and follow the prompts. The Output window tells you when the install is finished.
. moniker range=»<=vs-2019″
. moniker-end . moniker range=»>=vs-2022″
. moniker-end
Now you can use Visual Studio to create a model based on the Northwind database.
Create the model
Right-click on the project node in Solution Explorer and choose Add > New Item. In the left pane, under the C# node, choose Data and in the middle pane, choose ADO.NET Entity Data Model.

. moniker range=»<=vs-2019″ . moniker-end . moniker range=»>=vs-2022″ alt=»Screenshot of Entity Framework Model New Item.» width=»» /> . moniker-end
Call the model Northwind_model and choose Add. The Entity Data Model Wizard opens. Choose EF Designer from database and then click Next.

In the next screen, choose your LocalDB Northwind connection (for example, (localdb)\MSSQLLocalDB), specify the Northwind database, and click Next.
If you don’t see a connection, choose New Connection, then in the Choose Data Source dialog box, choose Microsoft SQL Server, choose Continue and in the Connection Properties dialog box, enter (localdb)\MSSQLLocalDB and under Select or enter a database name, choose Northwind, then press OK.
If prompted, choose the version of Entity Framework you are using.

In the next page of the wizard, choose which tables, stored procedures, and other database objects to include in the Entity Framework model. Expand the dbo node in the tree view and choose Customers, Orders, and Order Details. Leave the defaults checked and click Finish.

The wizard generates the C# classes that represent the Entity Framework model. The classes are plain old C# classes and they are what we databind to the WPF user interface. The .edmx file describes the relationships and other metadata that associates the classes with objects in the database. The .tt files are T4 templates that generate the code that operates on the model and saves changes to the database. You can see all these files in Solution Explorer under the Northwind_model node:

. moniker range=»<=vs-2019″ . moniker-end . moniker range=»>=vs-2022″ alt=»Screenshot showing Solution Explorer Entity Framework model files» width=»» /> . moniker-end
The designer surface for the .edmx file enables you to modify some properties and relationships in the model. We are not going to use the designer in this walkthrough.
The .tt files are general purpose and you need to tweak one of them to work with WPF databinding, which requires ObservableCollections. In Solution Explorer, expand the Northwind_model node until you find Northwind_model.tt. (Make sure you are not in the .Context.tt file, which is directly below the .edmx file.)
Replace the two occurrences of xref:System.Collections.ICollection with xref:System.Collections.ObjectModel.ObservableCollection%601.
Replace the first occurrence of xref:System.Collections.Generic.HashSet%601 with xref:System.Collections.ObjectModel.ObservableCollection%601 around line 51. Do not replace the second occurrence of HashSet.
Replace the only occurrence of xref:System.Collections.Generic (around line 431) with xref:System.Collections.ObjectModel.
Press F5 or Ctrl+F5 to build and run the project. When the application first runs, the model classes are visible to the data sources wizard.
Now you are ready to hook up this model to the XAML page so that you can view, navigate, and modify the data.
Databind the model to the XAML page
It is possible to write your own databinding code, but it is much easier to let Visual Studio do it for you.
From the main menu, choose Project > Add new data source to bring up the Data Source Configuration Wizard. Choose Object because you are binding to the model classes, not to the database:

Expand the node for your project, and select Customer. (Sources for Orders are automatically generated from the Orders navigation property in Customer.)
. moniker range=»<=vs-2019″
. moniker-end . moniker range=»>=vs-2022″
. moniker-end
Click Finish.
Navigate to MainWindow.xaml in Code View. We’re keeping the XAML simple for the purposes of this example. Change the title of MainWindow to something more descriptive, and increase its Height and Width to 600 x 800 for now. You can always change it later. Now add these three row definitions to the main grid, one row for the navigation buttons, one for the customer’s details, and one for the grid that shows their orders:
Now open MainWindow.xaml so that you’re viewing it in the designer. This causes the Data Sources window to appear as an option in the Visual Studio window margin next to the Toolbox. Click on the tab to open the window, or else press Shift+Alt+D or choose View > Other Windows > Data Sources. We are going to display each property in the Customers class in its own individual text box. First, click on the arrow in the Customers combo box and choose Details. Then, drag the node onto the middle part of the design surface so that the designer knows you want it to go in the middle row. If you misplace it, you can specify the row manually later in the XAML ( Grid.Row=»1″ ). By default, the controls are placed vertically in a grid element, but at this point, you can arrange them however you like on the form. For example, it might make sense to put the Name text box on top, above the address. The sample application for this article reorders the fields and rearranges them into two columns.
. moniker range=»<=vs-2019″
. moniker-end . moniker range=»>=vs-2022″
. moniker-end
In the XAML view, you can now see a new Grid element in row 1 (the middle row) of the parent Grid. The parent Grid has a DataContext attribute that refers to a xref:System.Windows.Data.CollectionViewSource that’s been added to the Windows.Resources element. Given that data context, when the first text box binds to Address, that name is mapped to the Address property in the current Customer object in the CollectionViewSource .
When a customer is visible in the top half of the window, you want to see their orders in the bottom half. You show the orders in a single grid view control. For master-detail databinding to work as expected, it is important that you bind to the Orders property in the Customers class, not to the separate Orders node. Drag the Orders property of the Customers class to the lower half of the form, so that the designer puts it in row 2:

. moniker range=»vs-2019″ . moniker-end . moniker range=»>=vs-2022″ alt=»Screenshot showing Orders classes dragged and dropped as a grid.» width=»» /> . moniker-end
Visual Studio has generated all the binding code that connects the UI controls to events in the model. All you need to do, in order to see some data, is to write some code to populate the model. First, navigate to MainWindow.xaml.cs and add a data member to the MainWindow class for the data context. This object, which has been generated for you, acts something like a control that tracks changes and events in the model. You’ll also add CollectionViewSource data members for customers and orders, and the associated constructor initialization logic to the existing constructor MainWindow() . The top of the class should look like this:
. code language=»csharp» source=»../data-tools/codesnippet/CSharp/CreateWPFDataApp/MainWindow.xaml.cs» .
If it’s not there already, add a using directive for System.Data.Entity to bring the Load extension method into scope:
Now, scroll down and find the Window_Loaded event handler. Notice that Visual Studio has added a CollectionViewSource object. This represents the NorthwindEntities object that you selected when you created the model. You added that already, so you don’t need it here. Let’s replace the code in Window_Loaded so that the method now looks like this:
. code language=»csharp» source=»../data-tools/codesnippet/CSharp/CreateWPFDataApp/MainWindow.xaml.cs» .
Press F5. You should see the details for the first customer that was retrieved into the CollectionViewSource. You should also see their orders in the data grid. The formatting isn’t great, so let’s fix that up. You can also create a way to view the other records and do basic CRUD operations.
Adjust the page design and add grids for new customers and orders
The default arrangement produced by Visual Studio is not ideal for your application, so we’ll provide the final XAML here to copy into your code. You also need some «forms» (which are actually Grids) to enable the user to add a new customer or order. In order to be able to add a new customer and order, you need a separate set of text boxes that are not data-bound to the CollectionViewSource . You’ll control which grid the user sees at any given time by setting the Visible property in the handler methods. Finally, you add a Delete button to each row in the Orders grid to enable the user to delete an individual order.
First, add these styles to the Windows.Resources element in MainWindow.xaml:
Next, replace the entire outer Grid with this markup:
Add buttons to navigate, add, update, and delete
In Windows Forms applications, you get a BindingNavigator object with buttons for navigating through rows in a database and doing basic CRUD operations. WPF does not provide a BindingNavigator, but it is easy enough to create one. You do that with buttons inside a horizontal StackPanel, and associate the buttons with Commands that are bound to methods in the code behind.
There are four parts to the command logic: (1) the commands, (2) the bindings, (3) the buttons, and (4) the command handlers in the code-behind.
Add commands, bindings, and buttons in XAML
First, add the commands in the MainWindow.xaml file inside the Windows.Resources element:
A CommandBinding maps a RoutedUICommand event to a method in the code behind. Add this CommandBindings element after the Windows.Resources closing tag:
Now, add the StackPanel with the navigation, add, delete, and update buttons. First, add this style to Windows.Resources :
Second, paste this code just after the RowDefinitions for the outer Grid element, toward the top of the XAML page:
Add command handlers to the MainWindow class
The code-behind is minimal except for the add and delete methods. Navigation is performed by calling methods on the View property of the CollectionViewSource. The DeleteOrderCommandHandler shows how to perform a cascade delete on an order. We have to first delete the Order_Details that are associated with it. The UpdateCommandHandler adds a new customer or order to the collection, or else just updates an existing customer or order with the changes that the user made in the text boxes.
Add these handler methods to the MainWindow class in MainWindow.xaml.cs. If your CollectionViewSource for the Customers table has a different name, then you need to adjust the name in each of these methods:
. code language=»csharp» source=»../data-tools/codesnippet/CSharp/CreateWPFDataApp/MainWindow.xaml.cs» .
Run the application
To start debugging, press F5. You should see customer and order data populated in the grid, and the navigation buttons should work as expected. Click on Commit to add a new customer or order to the model after you have entered the data. Click on Cancel to back out of a new customer or new order form without saving the data. You can make edits to existing customers and orders directly in the text boxes, and those changes are written to the model automatically.