Real-World Example: Building a Simple Blog with Dapper in .NET Core

Real-World Example: Building a Simple Blog with Dapper in .NET Core

Dapper is a lightweight and high-performance micro-ORM that provides direct SQL execution while still offering powerful object mapping capabilities. In this article, we'll build a simple blog application that demonstrates CRUD operations on articles using Dapper for data access.

 

Project Setup

1. Create a .NET Core Web API Project

Open a terminal and run:

dotnet new webapi -n DapperBlogApp

cd DapperBlogApp

2. Install Required Packages

To use Dapper, install the necessary NuGet packages:

dotnet add package Dapper

dotnet add package System.Data.SqlClient

3. Set Up the Database

Create a simple Articles table in SQL Server:

CREATE TABLE Articles (

    Id INT PRIMARY KEY IDENTITY,

    Title NVARCHAR(200) NOT NULL,

    Content NVARCHAR(MAX) NOT NULL,

    Author NVARCHAR(100) NOT NULL,

    CreatedAt DATETIME DEFAULT GETDATE()

);

 

Building the Data Access Layer with Dapper

1. Define the Article Model

public class Article

{

    public int Id { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public string Author { get; set; }

    public DateTime CreatedAt { get; set; }

}

2. Implement the Repository Pattern

Create a repository to handle database operations using Dapper.

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using Dapper;

 

public class ArticleRepository

{

    private readonly string _connectionString;

 

    public ArticleRepository(string connectionString)

    {

        _connectionString = connectionString;

    }

 

    public IEnumerable<Article> GetAll()

    {

        using (var connection = new SqlConnection(_connectionString))

        {

            return connection.Query<Article>("SELECT * FROM Articles");

        }

    }

 

    public Article GetById(int id)

    {

        using (var connection = new SqlConnection(_connectionString))

        {

            return connection.QuerySingleOrDefault<Article>("SELECT * FROM Articles WHERE Id = @Id", new { Id = id });

        }

    }

 

    public void Create(Article article)

    {

        using (var connection = new SqlConnection(_connectionString))

        {

            var sql = "INSERT INTO Articles (Title, Content, Author) VALUES (@Title, @Content, @Author)";

            connection.Execute(sql, article);

        }

    }

 

    public void Update(Article article)

    {

        using (var connection = new SqlConnection(_connectionString))

        {

            var sql = "UPDATE Articles SET Title = @Title, Content = @Content, Author = @Author WHERE Id = @Id";

            connection.Execute(sql, article);

        }

    }

 

    public void Delete(int id)

    {

        using (var connection = new SqlConnection(_connectionString))

        {

            connection.Execute("DELETE FROM Articles WHERE Id = @Id", new { Id = id });

        }

    }

}

 

Building the API Controller

1. Implement the Article Controller

using Microsoft.AspNetCore.Mvc;

using System.Collections.Generic;

 

[ApiController]

[Route("api/[controller]")]

public class ArticlesController : ControllerBase

{

    private readonly ArticleRepository _repository;

 

    public ArticlesController(ArticleRepository repository)

    {

        _repository = repository;

    }

 

    [HttpGet]

    public ActionResult<IEnumerable<Article>> Get()

    {

        return Ok(_repository.GetAll());

    }

 

    [HttpGet("{id}")]

    public ActionResult<Article> Get(int id)

    {

        var article = _repository.GetById(id);

        if (article == null) return NotFound();

        return Ok(article);

    }

 

    [HttpPost]

    public IActionResult Create(Article article)

    {

        _repository.Create(article);

        return Created("", article);

    }

 

    [HttpPut("{id}")]

    public IActionResult Update(int id, Article article)

    {

        var existingArticle = _repository.GetById(id);

        if (existingArticle == null) return NotFound();

 

        article.Id = id;

        _repository.Update(article);

        return NoContent();

    }

 

    [HttpDelete("{id}")]

    public IActionResult Delete(int id)

    {

        _repository.Delete(id);

        return NoContent();

    }

}

 

Configuring Dependency Injection in Program.cs

Update Program.cs to register the repository and configure the database connection.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

 

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddSingleton(new ArticleRepository(connectionString));

 

var app = builder.Build();

app.UseAuthorization();

app.MapControllers();

app.Run();

In appsettings.json, define the connection string:

"ConnectionStrings": {

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

}

 

Testing the Blog API

You can test the API using Postman or Swagger. Here are sample requests:

  • Create an article: (POST api/articles)

{

    "title": "Getting Started with Dapper",

    "content": "Dapper is a fast and efficient micro-ORM...",

    "author": "John Doe"

}

  • Get all articles: (GET api/articles)
  • Get a single article by ID: (GET api/articles/1)
  • Update an article: (PUT api/articles/1)
  • Delete an article: (DELETE api/articles/1)

 

Conclusion

This article demonstrated how to build a simple blog application using Dapper in .NET Core. We structured our application with a repository pattern, created a RESTful API, and optimized database interactions using Dapper’s high-performance capabilities.

 

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular