First example

Dapper supports many databases. We will use MySQL as our example here.

You need to have MySQL installed on your system beforehand.

Once MySQL is installed, create a new database.

Then create your database tables.

Getting Started

1. Install the NuGet Packages

Two packages must be installed together:

  1. Dapper (Core micro‑ORM library)
Install-Package Dapper
  1. MySql.Data (MySQL database driver, provides MySqlConnection)

Dapper does not ship with database drivers. You need to install an extra driver to work with MySQL.

2. Create Database Tables
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `StudentID` int NOT NULL AUTO_INCREMENT,
  `StudentName` text,
  `Age` int,
  `ClassName` text,
  PRIMARY KEY (`StudentID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;Code language: SQL (Structured Query Language) (sql)

C# Entity Class

Match property names with table column names for automatic Dapper mapping.

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
    public string ClassName { get; set; }
}Code language: C# (cs)

Rule: Column‑property mapping is case‑insensitive. Matching names is sufficient.

Configuration File

App.config

Correction for original screenshot: Do not set providerName to Oracle. This entry is unnecessary for MySQL and can be removed entirely.

Configure your connection string

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <connectionStrings>
    <add name="StudentConnection"
         connectionString="Server=localhost;Database=mydb;Uid=root;Pwd=root"/>
  </connectionStrings>
</configuration>Code language: HTML, XML (xml)

Sample Code

using System;
using System.Collections.Generic;
using System.Data;
using Dapper;
using MySql.Data.MySqlClient;
using System.Configuration;

class Program
{
    static void Main(string[] args)
    {
        List<Student> studentList = new List<Student>();

        // Read connection string from configuration
        string connStr = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;

        // 1. Initialize IDbConnection database connection
        using (IDbConnection db = new MySqlConnection(connStr))
        {
            // 2. Write SQL statement, 3. Execute query via Dapper extension for automatic entity mapping
            string sql = "SELECT * FROM student";
            studentList = db.Query<Student>(sql).ToList();

            Console.WriteLine($"Total students: {studentList.Count}");
        }
        Console.ReadKey();
    }
}Code language: C# (cs)

Three‑Step Dapper Workflow

  1. Instantiate an IDbConnection database connection object (MySqlConnection/SqlConnection)
  2. Write raw SQL statements to perform CRUD operations
  3. Pass SQL and parameters into Dapper extension methods (Query/Execute)

SQL Injection

Always use parameterized queries to fully prevent SQL injection.
Concatenating strings to build SQL introduces injection vulnerabilities.

string sql = "SELECT * FROM student WHERE StudentID = @Id";
var stu = db.QueryFirstOrDefault<Student>(sql, new { Id = 1 });Code language: C# (cs)

First example

Leave a Reply

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