Getting Started with Dapper in .NET Core

Getting Started with Dapper in .NET Core

Dapper is a lightweight and high-performance micro-ORM (Object Relational Mapper) for .NET that enables efficient database interactions. It is ideal for applications that prioritize speed and minimal overhead, offering a streamlined alternative to Entity Framework. This guide provides a comprehensive approach to integrating Dapper into your .NET Core projects.

 

1. Installing Dapper

To install Dapper, use the following command in your terminal or command prompt:

dotnet add package Dapper

Alternatively, you can install it via the NuGet Package Manager in Visual Studio.

 

2. Setting Up Database Connection

We'll use SQL Server for this example.

Configure Connection String

Add your database connection string to appsettings.json:

{

  "ConnectionStrings": {

    "DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DB;User Id=YOUR_USER;Password=YOUR_PASSWORD;"

  }

}

Inject Database Connection in Program.cs

Use dependency injection (DI) to provide an IDbConnection instance:

using Microsoft.Data.SqlClient;

using System.Data;

 

var builder = WebApplication.CreateBuilder(args);

 

builder.Services.AddScoped<IDbConnection>(sp =>

    new SqlConnection(builder.Configuration.GetConnectionString("DefaultConnection")));

 

var app = builder.Build();

 

// API endpoints will be added here

 

app.Run();

 

3. Defining the Product Class

Create a Product class to represent your data model:

public class Product

{

    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

}

 

4. Executing Queries with Dapper (Asynchronous)

Dapper makes it easy to execute database operations using simple SQL queries.

Retrieving Data (GET)

app.MapGet("/products", async (IDbConnection db) =>

{

    try

    {

        string sql = "SELECT * FROM Products";

        var products = await db.QueryAsync<Product>(sql);

        return Results.Ok(products);

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

Inserting Data (POST)

app.MapPost("/products", async (Product newProduct, IDbConnection db) =>

{

    try

    {

        string insertQuery = "INSERT INTO Products (Name, Price) OUTPUT INSERTED.Id VALUES (@Name, @Price)";

        newProduct.Id = await db.ExecuteScalarAsync<int>(insertQuery, newProduct);

        return Results.Created($"/products/{newProduct.Id}", newProduct);

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

Updating Data (PUT)

app.MapPut("/products/{id}", async (int id, Product updatedProduct, IDbConnection db) =>

{

    try

    {

        string updateQuery = "UPDATE Products SET Name = @Name, Price = @Price WHERE Id = @Id";

        await db.ExecuteAsync(updateQuery, new { updatedProduct.Name, updatedProduct.Price, Id = id });

        return Results.Ok(new { Message = "Product updated successfully." });

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

Deleting Data (DELETE)

app.MapDelete("/products/{id}", async (int id, IDbConnection db) =>

{

    try

    {

        string deleteQuery = "DELETE FROM Products WHERE Id = @Id";

        await db.ExecuteAsync(deleteQuery, new { Id = id });

        return Results.Ok(new { Message = "Product deleted successfully." });

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

 

5. Key Best Practices

  • Efficient Connection Management: Use dependency injection to manage IDbConnection lifecycle efficiently.
  • Asynchronous Execution: Always use asynchronous methods (QueryAsync, ExecuteAsync, ExecuteScalarAsync) to improve application responsiveness.
  • Error Handling: Implement try-catch blocks to handle database errors gracefully.
  • SQL Optimization: Use parameterized queries (@parameterName) to prevent SQL injection.
  • Proper API Responses: Return structured responses using the Results class for better API handling.
  • Configuration Management: Store connection strings in appsettings.json rather than hardcoding them in the source code.

 

6. Conclusion

Dapper provides a lightweight, efficient, and high-performance way to interact with databases in .NET Core applications. By following the steps outlined in this guide, you can integrate Dapper seamlessly into your project while following best practices for database access.

Would you like to explore advanced topics such as stored procedures, transactions, or bulk operations with Dapper? Let us know!

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced