Friday, March 24, 2023

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

 

using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Driver;

public class EmployeeRepository
{
    private readonly IMongoCollection<Employee> _employeeCollection;

    public EmployeeRepository(string connectionString, string databaseName)
    {
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase(databaseName);

        _employeeCollection = database.GetCollection<Employee>("employees");
    }

    public async Task<string> CreateEmployeeAsync(Employee employee)
    {
        await _employeeCollection.InsertOneAsync(employee);
        return employee.Id;
    }

    public async Task<IEnumerable<Employee>> GetEmployeesAsync()
    {
        var employees = await _employeeCollection.FindAsync(_ => true);
        return await employees.ToListAsync();
    }

    public async Task<Employee> GetEmployeeByIdAsync(string id)
    {
        var filter = Builders<Employee>.Filter.Eq(e => e.Id, id);
        var employees = await _employeeCollection.FindAsync(filter);
        return await employees.FirstOrDefaultAsync();
    }

    public async Task<bool> UpdateEmployeeAsync(Employee employee)
    {
        var filter = Builders<Employee>.Filter.Eq(e => e.Id, employee.Id);
        var result = await _employeeCollection.ReplaceOneAsync(filter, employee);
        return result.ModifiedCount > 0;
    }

    public async Task<bool> DeleteEmployeeAsync(string id)
    {
        var filter = Builders<Employee>.Filter.Eq(e => e.Id, id);
        var result = await _employeeCollection.DeleteOneAsync(filter);
        return result.DeletedCount > 0;
    }
}


No comments:

Post a Comment

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