Introduction
The Dapper is a lightweight and efficient micro ORM (Object-Relational Mapping) library for .NET. It allows you to execute SQL queries and map the results to strongly typed objects. Dapper does not abstract away the database connection or query execution; instead, it focuses on optimizing the mapping process. Here’s an example of using Dapper for connection management and querying a database:
- Install Dapper:
Install the Dapper NuGet package in your project:
dotnet add package Dapper
- Create a Model:
Define a model class that corresponds to the table you want to query:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
- Query the Database with Dapper:
Here’s an example of querying a database using Dapper:
using System;
using System.Data.SqlClient;
using Dapper;
class Program
{
static void Main(string[] args)
{
string connectionString = "your_connection_string_here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Query data using Dapper
var products = connection.Query<Product>("SELECT * FROM Products");
foreach (var product in products)
{
Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
}
}
}
}
Replace "your_connection_string_here"
with your actual database connection string.
In this example, we create a SqlConnection
and open it within a using
block. Inside the block, we use the connection.Query
the method provided by Dapper to execute the SQL query and map the results to a list of Product
objects. The connection is automatically managed and closed when the using
block exits.
Dapper uses ADO.NET connections and commands under the hood, so you have full control over connection management, parameterization, and other aspects of the database interaction. It simplifies the process of querying the database and mapping results to objects while providing good performance.
Remember to handle exceptions and error cases appropriately in a production scenario. Dapper is widely used and well-documented, so you can find more advanced usage scenarios and features in the official Dapper documentation and examples.