Diving into ASP.NET Core with a dapper sounds like a great way to work with databases more straightforwardly. Dapper is a micro ORM (Object-Relational Mapping) that helps in handling database operations while keeping the SQL queries simple and efficient.
To get started with using Dapper in an ASP.NET Core application.
Step 1. Create a New ASP.NET Core Project
You can create a new ASP.NET Core project using Visual Studio or by using the .NET CLI with the command.
dotnet new web -n APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure
cd APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure
Step 2. Install the Dapper Package
Add the Dapper package to your project using the .NET CLI.
dotnet add package Dapper
Step 3. Set Up Database Connection
In your appsettings.json add your database connection string.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "YourDatabaseConnectionString"
},
"AllowedHosts": "*"
}
Step 4. Create a Model
Define a model class that represents the table structure in your database.
namespace APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.Model
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public string CategoryCategory { get; set; }
public string CategoryCategoryName { get; set; }
}
}
Dapper Db Connection
using System.Data;
namespace APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.ServiceContracts
{
public interface IDapperDbConnection
{
public IDbConnection CreateConnection();
}
}
Dapper Db Connection Class
using APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.ServiceContracts;
using Microsoft.Data.SqlClient;
using System.Data;
namespace APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.DapperDbConnection
{
public class DapperDbConnection: IDapperDbConnection
{
public readonly string _connectionString;
public DapperDbConnection(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection");
}
public IDbConnection CreateConnection()
{
return new SqlConnection(_connectionString);
}
}
}
Product Repository Interface
using APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.Model;
namespace APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.ServiceContracts
{
public interface IProductRepository
{
Task<IEnumerable<Product>> GetAllProductsAsync();
Task<Product> GetProductByIdAsync(int id);
Task<int> CreateProductAsync(Product Product);
Task<bool> UpdateProductAsync(Product Product);
Task<bool> DeleteProductAsync(int id);
}
}
Create SQL Stored Procedures
GetAllProducts Store Procedure
CREATE PROCEDURE StpGetAllProducts
AS
BEGIN
SELECT * FROM Products;
END
StpGetProductById Store Procedure
CREATE PROCEDURE StpGetProductById
@Id INT
AS
BEGIN
SELECT * FROM Products WHERE Id = @Id;
END
StpAddProduct Store Procedure
CREATE PROCEDURE StpAddProduct
@Name NVARCHAR(100),
AS
BEGIN
INSERT INTO Products (Name)
VALUES (@Name);
SELECT SCOPE_IDENTITY();
END
StpUpdateProduct Store Procedure
CREATE PROCEDURE StpUpdateProduct
@Id INT,
@Name NVARCHAR(100)
AS
BEGIN
UPDATE Products
SET Name = @Name
WHERE Id = @Id;
END
StpDeleteProduct Store Procedure
CREATE PROCEDURE StpDeleteProduct
@Id INT
AS
BEGIN
DELETE FROM Products WHERE Id = @Id;
END
Product Repository Implementation
using APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.Model;
using APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.ServiceContracts;
using Dapper;
using System.Data;
namespace APIDevelopmentUsingAspNetCoreWithDapperAndStoredProcedure.Repository
{
public class ProductRepository : IProductRepository
{
private readonly IDapperDbConnection _dapperDbConnection;
public ProductRepository(IDapperDbConnection dapperDbConnection)
{
_dapperDbConnection = dapperDbConnection;
}
public async Task<IEnumerable<Product>> GetAllProductsAsync()
{
using(IDbConnection db = _dapperDbConnection.CreateConnection())
{
return await db.QueryAsync<Product>("StpGetAllProducts", commandType: CommandType.StoredProcedure);
}
}
public async Task<Product> GetProductByIdAsync(int id)
{
using(IDbConnection db = _dapperDbConnection.CreateConnection())
{
var parameters = new { Id = id };
return await db.QueryFirstOrDefaultAsync<Product>("StpGetProductById", parameters, commandType: CommandType.StoredProcedure);
}
}
public async Task<int> CreateProductAsync(Product product)
{
if(product == null)
{
throw new ArgumentNullException(nameof(product));
}
using(IDbConnection db = _dapperDbConnection.CreateConnection())
{
return await db.ExecuteScalarAsync<int>("StpAddProduct",
new
{
product.Name,
// Other parameters
},
commandType: CommandType.StoredProcedure);
}
}
public async Task<bool> UpdateProductAsync(Product product)
{
if(product == null)
{
throw new ArgumentNullException(nameof(product));
}
using(IDbConnection db = _dapperDbConnection.CreateConnection())
{
int rowsAffected = await db.ExecuteAsync("StpUpdateProduct",
new
{
product.Id,
product.Name,
// Other parameters
},
commandType: CommandType.StoredProcedure);
return rowsAffected > 0;
}
}
public async Task<bool> DeleteProductAsync(int id)
{
using(IDbConnection db = _dapperDbConnection.CreateConnection())
{
int rowsAffected = await db.ExecuteAsync("StpDeleteProduct",
new { Id = id },
commandType: CommandType.StoredProcedure);
return rowsAffected > 0;
}
}
}
}

jose loraPosted Dec 27, 2023, 8:53 PM
Excelent work