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
dotnet new webapi -n DapperBlogApp
cd DapperBlogApp
2. Install Required Packages
dotnet add package Dapper
dotnet add package System.Data.SqlClient
3. Set Up the Database
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
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
Program.cs
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();
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DB;User Id=YOUR_USER;Password=YOUR_PASSWORD;"
}
}
๐งช Testing the Blog API
- Create Article: POST /api/articles
- Get All Articles: GET /api/articles
- Get by ID: GET /api/articles/1
- Update: PUT /api/articles/1
- Delete: DELETE /api/articles/1
{
"title": "Getting Started with Dapper",
"content": "Dapper is a fast and efficient micro-ORM...",
"author": "John Doe"
}
✅ 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
Post a Comment