Dapper in .Net 6

Dikshya SubediDikshya Subedi
2 min read

Dapper is a popular lightweight Object-Relational Mapping (ORM) library for .NET applications. It was developed by Stack Overflow to provide a simple and efficient way to work with databases while minimizing the performance overhead typically associated with more complex ORM frameworks.

  1. Install Dapper: You can add Dapper to your project using NuGet. Open the NuGet

Package Manager Console and run the following command:

Install-Package Dapper
  1. For SQL Server, you'll need to install the SQL Server database provider package. In a .NET 6 project, you can follow these steps to install the SQL Server client package:

Open a terminal or the NuGet Package Manager Console in Visual Studio.

Run the following command to install the SQL Server client package:

Install-Package Microsoft.Data.SqlClient

You can also install packages using the NuGet Package Manager directly from within Visual Studio.

  1. Set Up Database Connection:

     using System.Data.SqlClient;
    
     namespace YourNamespace { 
       public class DatabaseContext 
       { 
          private readonly string _connectionString;
    
          public DatabaseContext(string connectionString) 
          { 
            connectionString = $"Data Source={Environment.GetEnvironmentVariable("DBHOST")};Initial Catalog={Environment.GetEnvironmentVariable("DB_NAME")};User ID={Environment.GetEnvironmentVariable("DB_USER")};Password={Environment.GetEnvironmentVariable("DB_PASSWORD")};pooling='true';Max Pool Size=200000;"; 
          }
    
          public SqlConnection CreateConnection() 
          { 
             return new SqlConnection(_connectionString); 
          } 
        } 
     }
    
  1. Register in the Program.cs file

      var builder = WebApplication.CreateBuilder(args); 
     ...... ... 
     builder.Services.AddTransient();
    
     ..... 
     var app = builder.Build();
    

    DatabaseContext will be registered as a transient service, which means a new instance will be created each time it's requested from the service provider.

0
Subscribe to my newsletter

Read articles from Dikshya Subedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dikshya Subedi
Dikshya Subedi