Logo

dev-resources.site

for different kinds of informations.

C# | Entity Framework Generic Repository with SOLID Design Pattern

Published at
7/23/2024
Categories
microsoft
csharp
entityframework
solidprinciples
Author
hbolajraf
Author
9 person written this
hbolajraf
open
C# | Entity Framework Generic Repository with SOLID Design Pattern
Note
You can check other posts on my personal website: https://hbolajraf.net

Entity Framework Generic Repository with SOLID Design Pattern in C

In this guide, we'll explore how to create a generic repository in a C# application using Entity Framework while adhering to SOLID design principles. A generic repository allows you to interact with the database in a more organized and reusable manner.

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Basic knowledge of C# and Entity Framework.
  • An existing C# project with Entity Framework setup.

SOLID Design Principles

We'll focus on the following SOLID principles:

  1. Single Responsibility Principle (SRP): Each class should have a single reason to change.
  2. Open-Closed Principle (OCP): Software entities (classes, modules, functions) should be open for extension but closed for modification.
  3. Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types.
  4. Interface Segregation Principle (ISP): A client should not be forced to implement interfaces they do not use.
  5. Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

Creating a Generic Repository

  1. Create a Generic Repository Interface:
   public interface IRepository<T> where T : class
   {
       Task<T> GetByIdAsync(int id);
       Task<IEnumerable<T>> GetAllAsync();
       Task AddAsync(T entity);
       Task UpdateAsync(T entity);
       Task DeleteAsync(T entity);
   }
Enter fullscreen mode Exit fullscreen mode
  1. Implement the Generic Repository:
   public class Repository<T> : IRepository<T> where T : class
   {
       private readonly DbContext _context;

       public Repository(DbContext context)
       {
           _context = context;
       }

       public async Task<T> GetByIdAsync(int id)
       {
           return await _context.Set<T>().FindAsync(id);
       }

       public async Task<IEnumerable<T>> GetAllAsync()
       {
           return await _context.Set<T>().ToListAsync();
       }

       public async Task AddAsync(T entity)
       {
           await _context.Set<T>().AddAsync(entity);
       }

       public async Task UpdateAsync(T entity)
       {
           _context.Set<T>().Update(entity);
       }

       public async Task DeleteAsync(T entity)
       {
           _context.Set<T>().Remove(entity);
       }
   }
Enter fullscreen mode Exit fullscreen mode

Using the Generic Repository

  1. Dependency Injection: In your application's startup or configuration, inject the repository into your services.
   services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
Enter fullscreen mode Exit fullscreen mode
  1. Using the Repository: In your services or controllers, use the generic repository to interact with the database.
   public class MyService
   {
       private readonly IRepository<MyEntity> _repository;

       public MyService(IRepository<MyEntity> repository)
       {
           _repository = repository;
       }

       public async Task<MyEntity> GetEntityById(int id)
       {
           return await _repository.GetByIdAsync(id);
       }

       // Implement other methods as needed
   }
Enter fullscreen mode Exit fullscreen mode
  1. Apply SOLID Principles: Ensure your services adhere to SOLID principles, like separating concerns and following the Single Responsibility Principle, when implementing business logic.

What Next?

Creating a generic repository using Entity Framework and adhering to SOLID design principles can make your C# application more maintainable and scalable. By using this pattern, you can easily extend and modify your data access layer without affecting the rest of your application.
Remember to adapt the code and principles to your specific project's needs and requirements.

entityframework Article's
30 articles in total
Favicon
Entity Framework Core Code First
Favicon
Code First Approach with Entity Framework.
Favicon
Custom NET8 Entity Framework Core Generic Repository
Favicon
Link Many To Many entities with shadow join-table using Entity Framework Core
Favicon
Running Entity Framework Core Migrations with Optimizely CMS 12
Favicon
Check Pagination in .NET: With and Without Entity Framework
Favicon
EF Core 6 - correct types halving the execution time!
Favicon
EF Core 6 - This SqlTransaction has completed; it is no longer usable.
Favicon
Entity Framework Core Tutorial:Introduction to Entity Framework Core
Favicon
ReadOnly DbContext with Entity Framework
Favicon
[KOSD] Multiple Parallel Operations in Entity Framework Core (.NET 8)
Favicon
Entity Framework in .net core 6.0 - Code first and Database first approach
Favicon
5 EF Core Features You Need To Know
Favicon
C# | Best Practices for Pagination using EF Core 8
Favicon
C# | Using Entity Framework with PostgreSQL Database
Favicon
C# | Entity Framework Generic Repository with SOLID Design Pattern
Favicon
C# | Entity Framework Issues and Troubleshooting
Favicon
Entity Framework Core with Scalar Functions
Favicon
Prefer Empty Objects over Compiler tricks
Favicon
The Differences Between EntityFramework .Add and .AddAsync
Favicon
Entity FrameWork
Favicon
Load Appointments on Demand in Blazor Scheduler using Entity Framework Core
Favicon
Finding the Right Balance: Clean Architecture and Entity Framework in Practice
Favicon
Compilation steps in EF Core
Favicon
Learning is another full-time job.
Favicon
How To Use EF Core Interceptors
Favicon
Using Entity Framework Core 8 Owned Types HasData()
Favicon
Simple Event-Sourcing with EF Core and SQL Server
Favicon
Delete in EF 8 !
Favicon
Optimizing Database Access with Entity Framework - Lazy Loading vs. Eager Loading

Featured ones: