Dapper in .Net 6
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.
- 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
- 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.
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); } } }
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.
Comments
Join the discussionNo comments yet. Be the first to comment.