using System.Collections.Generic;
using System.Data.SqlClient;
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public class ProductRepository
public static List<Product> GetAllProducts(string connectionString)
if (string.IsNullOrEmpty(connectionString))
Console.WriteLine("Connection string cannot be null or empty.");
return new List<Product>();
List<Product> products = new List<Product>();
using (SqlConnection connection = new SqlConnection(connectionString))
string query = "SELECT ProductId, ProductName, UnitPrice FROM Products";
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataReader reader = command.ExecuteReader())
Product product = new Product
ProductId = reader.GetInt32(0),
ProductName = reader.GetString(1),
UnitPrice = reader.GetDecimal(2)
Console.WriteLine($"A SqlException occurred: {ex.Message}");
return new List<Product>();
Console.WriteLine($"An exception occurred: {ex.Message}");
return new List<Product>();
public static void Main(string[] args)
string connectionString = "Server=localhost;Database=YourDatabaseName;User Id=YourUserId;Password=YourPassword;";
List<Product> products = GetAllProducts(connectionString);
Console.WriteLine("Products:");
foreach (Product product in products)
Console.WriteLine($"- ProductId: {product.ProductId}, ProductName: {product.ProductName}, UnitPrice: {product.UnitPrice}");
Console.WriteLine("No products found or an error occurred.");