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's ideal for applications prioritizing speed and minimal overhead, offering a streamlined alternative to Entity Framework. This guide provides an enhanced approach to integrating Dapper into your .NET Core projects.

 

1. Installing Dapper

Install the Dapper NuGet package using the following command:

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

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:

public class Product

{

    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

}

 

4. Executing Queries with Dapper (Asynchronous)

We'll create simple web API endpoints using Dapper and the previously injected IDbConnection.

 

Example: 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);

    }

});

 

Example: Inserting Data (POST)

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

{

    try

    {

        string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";

        await db.ExecuteAsync(insertQuery, newProduct);

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

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

 

Example: Updating Data (PUT)

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

{

    try

    {

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

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

        return Results.NoContent();

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

 

Example: 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.NoContent();

    }

    catch (Exception ex)

    {

        return Results.Problem(ex.Message);

    }

});

 

Key Improvements and Considerations:

IConfiguration for Connection String: We retrieve the connection string using builder.Configuration.GetConnectionString(), promoting configuration management.

Product Class Definition: The Product class is explicitly defined, clarifying the data structure.

Asynchronous Methods: We use Dapper's asynchronous methods (QueryAsync, ExecuteAsync) for better performance and responsiveness.

Error Handling: Basic try-catch blocks are included to handle potential database exceptions.

Dependency Injection: The IDbConnection is injected via .NET Core's dependency injection system.

Web API Endpoints: The examples demonstrate creating simple web API endpoints using MapGet, MapPost, MapPut, and MapDelete.

Using Results: The web api returns the correct results using the Results class.

Using the injected IDbConnection: The examples use the IDbConnection that is injected into the application.

 

Conclusion

Dapper provides a powerful and efficient way to interact with databases in .NET Core. By following these enhanced steps, you can integrate Dapper into your projects effectively, leveraging its speed and simplicity while adhering to best practices. Remember to adapt the connection string and queries to your specific database schema and application requirements.

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular