Let’s delve into the practical aspect of integrating Dapper into an ASP.NET Core application. Below is a step-by-step guide along with coding examples:
Step 1: Install Dapper NuGet Package
First, open your ASP.NET Core project in Visual Studio or your preferred IDE. Then, install the Dapper NuGet package using the Package Manager Console or the NuGet Package Manager:
Install-Package Dapper
Step 2: Configure Database Connection
Next, configure your database connection in the `appsettings.json` file:
{ "ConnectionStrings": {"DefaultConnection": "YourConnectionStringHere"} }
Step 3: Create a Model Class
Create a C# class to represent the entity you’ll be querying from the database. For example:
public class Product { public int Id {get; set;} public string Name {get; set;} public decimal Price {get; set;} }
Step 4: Implement Dapper Query
Now, let’s write a method to query data using Dapper in your ASP.NET Core application. Below is an example of how you can retrieve a list of products from the database:
using Dapper; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; public class ProductService { private readonly IConfiguration _config; public ProductService(IConfiguration config) { _config = config; } public async Task<IEnumerable<Product>> GetProductsAsync() { using IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")); return await db.QueryAsync<Product>("SELECT Id, Name, Price FROM Products"); } }
Step 5: Use Dependency Injection
Register the `ProductService` class in your ASP.NET Core startup file (`Startup.cs`):
public void ConfigureServices(IServiceCollection services) { // Other service registrations services.AddTransient<ProductService>(); }
Step 6: Use the ProductService in Your Controller
Finally, inject the `ProductService` into your controller and use it to retrieve products:
using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly ProductService _productService; public ProductController(ProductService productService) { _productService = productService; } [HttpGet] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { var products = await _productService.GetProductsAsync(); return Ok(products); } }
And there you have it! You’ve successfully integrated Dapper into your ASP.NET Core application and fetched data from the database using Dapper’s fluent API.
Happy coding!
CHECK : Using SignalR in ASP.NET Core for Real-Time Web Applications: Getting Started Guide