Sobes.tech
Junior — Middle

How have you structured interaction with the database in your projects?

sobes.tech AI

Answer from AI

In my projects, I usually structure interaction with the database as follows:

  1. Data Access Layer (DAL) — a separate layer or set of classes responsible for direct interaction with the database (e.g., through ORM or ADO.NET).
  2. Repositories — a pattern that encapsulates query logic and operations with specific entities, providing a convenient interface for business logic.
  3. Unit of Work — for managing transactions and data consistency.

Example in C# using Entity Framework:

public interface IRepository<T> where T : class
{
    Task<T> GetByIdAsync(int id);
    Task<IEnumerable<T>> GetAllAsync();
    void Add(T entity);
    void Remove(T entity);
}

public class Repository<T> : IRepository<T> where T : class
{
    protected readonly DbContext _context;
    public Repository(DbContext context) { _context = context; }

    public async Task<T> GetByIdAsync(int id) => await _context.Set<T>().FindAsync(id);
    public async Task<IEnumerable<T>> GetAllAsync() => await _context.Set<T>().ToListAsync();
    public void Add(T entity) => _context.Set<T>().Add(entity);
    public void Remove(T entity) => _context.Set<T>().Remove(entity);
}

This approach facilitates testing, support, and scaling of the project.