DEV Community

Ayush Pandey
Ayush Pandey

Posted on

What really Repository is in Asp.Net Core ?

What is a Repository?
A Repository acts as a bridge between your application’s services and the database.

Think of it like this:
Your Service contains the business logic – the rules, validations, and operations your app performs.Your DbContext represents the database connection and tables.The Repository sits in the middle, handling all database operations like Create, Read, Update, and Delete (CRUD).

By doing this:

  1. Your database logic is cleanly separated.

2.Your service doesn’t need to know how the database works.

3.Your code becomes easier to maintain, test, and extend.

Example: UserRepository
Here’s an example of a simple repository for managing users:

using backend_01.Core.User.Model;
using backend_01.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace backend_01.Infrastructure.Repository
{
    public class UserRepository
    {
        private readonly ApplicationDbContext _context;

        public UserRepository(ApplicationDbContext context)
        {
            _context = context; // DbContext injected via DI
        }

        public async Task<UserModel> CreateUser(UserModel user)
        {
           try
           {
               await _context.Users.AddAsync(user);
               await _context.SaveChangesAsync();
               return user;
           }
           catch (Exception ex)
           {
               throw new Exception($"Internal Server Error, Message: {ex.Message}");
           }
        }
}
}
Enter fullscreen mode Exit fullscreen mode

In our UserRepository, we first inject the ApplicationDbContext through the constructor using private readonly ApplicationDbContext _context; so that the repository can directly interact with the database. To create a new user, we define the CreateUser(UserModel user) method, where we await _context.Users.AddAsync(user); to add the entity and then await _context.SaveChangesAsync(); to persist the changes. For fetching users, we have GetUsers(), which uses await _context.Users.Take(10).ToListAsync(); to retrieve the first 10 users. Both methods are wrapped in try-catch blocks to handle errors gracefully and throw descriptive exceptions. This repository is then registered in Program.cs with builder.Services.AddScoped();, ensuring a new instance is created per HTTP request. Essentially, the repository acts as a bridge between the service layer and the database, centralizing all CRUD operations and keeping business logic in the service layer clean and focused.

Top comments (0)