Friday, March 24, 2023

How to implement async CRUD methods for an Employee model using Dapper with Oracle

 

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using Dapper;

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task<int> CreateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new OracleConnection(_connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Email, PhoneNumber) " +
                           "VALUES (:FirstName, :LastName, :Email, :PhoneNumber) " +
                           "RETURNING Id INTO :id";

            var parameters = new DynamicParameters();
            parameters.Add(":FirstName", employee.FirstName);
            parameters.Add(":LastName", employee.LastName);
            parameters.Add(":Email", employee.Email);
            parameters.Add(":PhoneNumber", employee.PhoneNumber);
            parameters.Add(":id", DbType.Int32, direction: ParameterDirection.Output);

            await connection.ExecuteAsync(query, parameters);

            return parameters.Get<int>(":id");
        }
    }

    public async Task<IEnumerable<Employee>> GetEmployeesAsync()
    {
        using (IDbConnection connection = new OracleConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees";

            return await connection.QueryAsync<Employee>(query);
        }
    }

    public async Task<Employee> GetEmployeeByIdAsync(int id)
    {
        using (IDbConnection connection = new OracleConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees WHERE Id = :id";

            return await connection.QuerySingleOrDefaultAsync<Employee>(query, new { id });
        }
    }

    public async Task<bool> UpdateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new OracleConnection(_connectionString))
        {
            string query = "UPDATE Employees SET FirstName = :FirstName, LastName = :LastName, " +
                           "Email = :Email, PhoneNumber = :PhoneNumber WHERE Id = :Id";

            int rowsAffected = await connection.ExecuteAsync(query, employee);

            return rowsAffected > 0;
        }
    }

    public async Task<bool> DeleteEmployeeAsync(int id)
    {
        using (IDbConnection connection = new OracleConnection(_connectionString))
        {
            string query = "DELETE FROM Employees WHERE Id = :id";

            int rowsAffected = await connection.ExecuteAsync(query, new { id });

            return rowsAffected > 0;
        }
    }
}


How to implement async CRUD methods for an Employee model using Dapper with MySQL

 

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Dapper;

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task<int> CreateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new MySqlConnection(_connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Email, PhoneNumber) " +
                           "VALUES (@FirstName, @LastName, @Email, @PhoneNumber);" +
                           "SELECT LAST_INSERT_ID()";

            return await connection.ExecuteScalarAsync<int>(query, employee);
        }
    }

    public async Task<IEnumerable<Employee>> GetEmployeesAsync()
    {
        using (IDbConnection connection = new MySqlConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees";

            return await connection.QueryAsync<Employee>(query);
        }
    }

    public async Task<Employee> GetEmployeeByIdAsync(int id)
    {
        using (IDbConnection connection = new MySqlConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees WHERE Id = @id";

            return await connection.QuerySingleOrDefaultAsync<Employee>(query, new { id });
        }
    }

    public async Task<bool> UpdateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new MySqlConnection(_connectionString))
        {
            string query = "UPDATE Employees SET FirstName = @FirstName, LastName = @LastName, " +
                           "Email = @Email, PhoneNumber = @PhoneNumber WHERE Id = @Id";

            int rowsAffected = await connection.ExecuteAsync(query, employee);

            return rowsAffected > 0;
        }
    }

    public async Task<bool> DeleteEmployeeAsync(int id)
    {
        using (IDbConnection connection = new MySqlConnection(_connectionString))
        {
            string query = "DELETE FROM Employees WHERE Id = @id";

            int rowsAffected = await connection.ExecuteAsync(query, new { id });

            return rowsAffected > 0;
        }
    }
}


 

How to implement async CRUD methods for an Employee model using Dapper with PostgreSQL

 You will need to install and add reference to the Npgsql package to communicate with PostgreSQL database.

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Npgsql;
using Dapper;

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task<int> CreateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new NpgsqlConnection(_connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Email, PhoneNumber) " +
                           "VALUES (@FirstName, @LastName, @Email, @PhoneNumber);" +
                           "SELECT CAST(CURRENT_VAL('employees_id_seq') AS INTEGER)";

            return await connection.ExecuteScalarAsync<int>(query, employee);
        }
    }

    public async Task<IEnumerable<Employee>> GetEmployeesAsync()
    {
        using (IDbConnection connection = new NpgsqlConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees";

            return await connection.QueryAsync<Employee>(query);
        }
    }

    public async Task<Employee> GetEmployeeByIdAsync(int id)
    {
        using (IDbConnection connection = new NpgsqlConnection(_connectionString))
        {
            string query = "SELECT * FROM Employees WHERE Id = @id";

            return await connection.QuerySingleOrDefaultAsync<Employee>(query, new { id });
        }
    }

    public async Task<bool> UpdateEmployeeAsync(Employee employee)
    {
        using (IDbConnection connection = new NpgsqlConnection(_connectionString))
        {
            string query = "UPDATE Employees SET FirstName = @FirstName, LastName = @LastName, " +
                           "Email = @Email, PhoneNumber = @PhoneNumber WHERE Id = @Id";

            int rowsAffected = await connection.ExecuteAsync(query, employee);

            return rowsAffected > 0;
        }
    }

    public async Task<bool> DeleteEmployeeAsync(int id)
    {
        using (IDbConnection connection = new NpgsqlConnection(_connectionString))
        {
            string query = "DELETE FROM Employees WHERE Id = @id";

            int rowsAffected = await connection.ExecuteAsync(query, new { id });

            return rowsAffected > 0;
        }
    }
}


Thursday, March 23, 2023

How to read data in .net from Oracle using Dapper

Following is an async C# method, that use the OracleConnection class to create a connection to the Oracle database. The QueryAsync method is called on the connection object to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. The AsList method is called on the result of the query to convert it to a list of Employee objects.

Note that you will need to add the reference to the Oracle.ManagedDataAccess.Client package.

 

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using Oracle.ManagedDataAccess.Client;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromOracleAsync()
{
    List<Employee> employees;
    string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=hostName)(PORT=portNumber))(CONNECT_DATA=(SERVER=DEDICATED)
(SERVICE_NAME=serviceName)));User Id=userName;Password=password;";
 
    using (IDbConnection connection = new OracleConnection(connectionString))
    {
        employees = (await connection.QueryAsync<Employee>("SELECT * FROM Employee")).AsList();
    }
   
    return employees;
}
 

Different ways to write a method that reads list of entities from SQL Server in C# language

There are different ways we can do same work. With evolution of .net technologies we have found different technologies to perform data operations. Here we will look at different ways of getting a list of employees from SQL Server database using different data access technologies.

Method-1: using ADO.NET

This method retrieves the employee list from the "Employee" table in the SQL Server database using a SELECT query, and maps the data to a list of Employee objects. Note that in this example, the Employee class has properties for the Id, Name, Department, and Salary fields in the database, and the SqlDataReader's Get methods are used to retrieve the values for each field from each record.

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

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public List<Employee> GetEmployeeListFromSqlServer()
{
    List<Employee> employees = new List<Employee>();
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
       
        while (reader.Read())
        {
            Employee employee = new Employee();
            employee.Id = reader.GetInt32(0);
            employee.Name = reader.GetString(1);
            employee.Department = reader.GetString(2);
            employee.Salary = reader.GetDecimal(3);
           
            employees.Add(employee);
        }
       
        reader.Close();
    }
   
    return employees;
}



Method-2: using ADO.NET async

In this async version of the method, the SqlConnection is opened asynchronously using await connection.OpenAsync(), and the SqlDataReader is created and executed asynchronously using await command.ExecuteReaderAsync(). The while loop that reads the data is also made asynchronous using await reader.ReadAsync(). Note that the using statements are still used to ensure proper disposal of resources.


using System.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees = new List<Employee>();
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
       
        using (SqlCommand command = new SqlCommand(query, connection))
        using (SqlDataReader reader = await command.ExecuteReaderAsync())
        {
            while (await reader.ReadAsync())
            {
                Employee employee = new Employee();
                employee.Id = reader.GetInt32(0);
                employee.Name = reader.GetString(1);
                employee.Department = reader.GetString(2);
                employee.Salary = reader.GetDecimal(3);
               
                employees.Add(employee);
            }
        }
    }
   
    return employees;
}



Method-3: using Dapper

In this async version of the method, the SqlConnection is opened asynchronously using await connection.OpenAsync(). The query is then executed asynchronously using Dapper's QueryAsync method, which returns a list of Employee objects already mapped to the data returned by the SQL query. The using statement is still used to ensure proper disposal of resources.

using System.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        employees = (await connection.QueryAsync<Employee>(query)).AsList();
    }
   
    return employees;
}


Method-4: using EF Core

In this async version of the method, a DbContextOptionsBuilder is used to configure the connection string and then used to create a new DbContext instance. The Set method is used to retrieve the DbSet<Employee>, and then the ToListAsync method is called to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. The using statement is still used to ensure proper disposal of resources. Note that you will need to add the appropriate NuGet packages and configure EF Core for your specific database provider.

 

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
   
    DbContextOptionsBuilder dbContextOptionsBuilder = new DbContextOptionsBuilder();
    dbContextOptionsBuilder.UseSqlServer(connectionString);
    using (var dbContext = new DbContext(dbContextOptionsBuilder.Options))
    {
        employees = await dbContext.Set<Employee>().ToListAsync();
    }
   
    return employees;
}
 


Method-5: LINQ to SQL:

In this async version of the method, a DataContext is used to connect to the database and a Table<Employee> is used to retrieve the table of Employee objects. The ToListAsync method is called on the Table<Employee> to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. Note that you will need to add the appropriate references to System.Data.Linq and configure the DataContext for your specific database provider. The using statement is still used to ensure proper disposal of resources.

using System.Data.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
   
    DataContext dataContext = new DataContext(connectionString);
    Table<Employee> employeeTable = dataContext.GetTable<Employee>();
   
    employees = await employeeTable.ToListAsync();
   
    return employees;
}