Friday, March 24, 2023

How to write async C# crud methods for Employee model from Apache Cassandra


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra;
using Cassandra.Mapping;

public class EmployeeRepository
{
    private readonly ISession _session;
    private readonly IMapper _mapper;

    public EmployeeRepository(string connectionString, string keyspace)
    {
        var cluster = Cluster.Builder()
            .AddContactPoint(connectionString)
            .Build();

        _session = cluster.Connect(keyspace);

        var mappingConfig = new MappingConfiguration()
            .Define<EmployeeMapping>();

        _mapper = new Mapper(_session, mappingConfig);
    }

    public async Task<string> CreateEmployeeAsync(Employee employee)
    {
        employee.Id = Guid.NewGuid().ToString();
        await _mapper.InsertAsync(employee);
        return employee.Id;
    }

    public async Task<IEnumerable<Employee>> GetEmployeesAsync()
    {
        var query = new SimpleStatement("SELECT * FROM employees");
        var result = await _mapper.FetchAsync<Employee>(query);
        return result.ToList();
    }

    public async Task<Employee> GetEmployeeByIdAsync(string id)
    {
        var query = new SimpleStatement("SELECT * FROM employees WHERE id = ?", id);
        var result = await _mapper.FetchAsync<Employee>(query);
        return result.FirstOrDefault();
    }

    public async Task<bool> UpdateEmployeeAsync(Employee employee)
    {
        var query = new SimpleStatement("UPDATE employees SET name = ?, email = ? WHERE id = ?",
            employee.Name, employee.Email, employee.Id);

        var result = await _session.ExecuteAsync(query);
        return result.WasApplied;
    }

    public async Task<bool> DeleteEmployeeAsync(string id)
    {
        var query = new SimpleStatement("DELETE FROM employees WHERE id = ?", id);
        var result = await _session.ExecuteAsync(query);
        return result.WasApplied;
    }
}


 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.