how to use Dapper in a .NET Core application to fetch data from a database

Install Dapper NuGet package:

dotnet add package Dapper



Code to fetch data using Dapper:

using Dapper;
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Program
{
    private static string connectionString = "YourConnectionStringHere";

    public static void Main()
    {
        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Fetch a single record
            var user = connection.QueryFirstOrDefault<User>("SELECT Id, Name FROM Users WHERE Id = @Id", new { Id = 1 });
            Console.WriteLine($"User: {user?.Name}");

            // Fetch multiple records
            var users = connection.Query<User>("SELECT Id, Name FROM Users").ToList();
            foreach (var u in users)
            {
                Console.WriteLine($"User: {u.Name}");
            }
        }
    }
}


Explanation:

QueryFirstOrDefault<T>: Fetches a single record or returns null if not found.

Query<T>: Fetches multiple records as an IEnumerable<T>.


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced